2017-10-08 23 views
3
聲明

我試圖做簡單的事情:如果在Lua

  • 程序打印第一條消息,並等待用戶輸入
  • 用戶類型在「玩」或「離開」
  • 如果用戶類型在「玩」程序打印「讓我們玩」並退出(現在)
  • 如果在「離開」程序打印「再見」用戶類型和退出
  • 如果東西比「玩」或「離開不同用戶類型「程序 打印第一個爛攤子年齡,等待用戶再次輸入

但是當前的代碼只是打印第一條消息2次,然後退出:

print("welcome. you have 2 options: play or leave. choose.") 
input = io.read() 

if input == "play" then 
print("let's play") 
end 

if input == "leave" then 
print("bye") 
end 

if input ~= "play" or "leave" then 
print("welcome. you have 2 options: play or leave. choose.") 
end 

這裏有什麼問題?

if (input ~= "play") or "leave" then 

字符串"leave",或與此有關的任何字符串,被認爲是truthy值:所理解的任何幫助,感謝

+0

什麼是「輸入」? – hjpotter92

+0

我編輯過的代碼是:input = io.read()。問題在於在任何用戶輸入程序之後再打印第一條消息並退出 – hexbreak

回答

4

if聲明將只執行一次。它不會跳轉到程序的其他部分。要做到這一點,你需要換一個while循環您輸入的代碼,並打破了,當你得到一個有效的響應:

while true do 
    print("welcome. you have 2 options: play or leave. choose.") 
    local input = io.read() 

    if input == "play" then 
    print("let's play") 
    break 
    elseif input == "leave" then 
    print("bye") 
    break 
    end 

end 

瞭解更多關於循環here

1

if input ~= "play" or "leave" then進行評估。

您需要兩個字符串比較,使用and

if input ~= "play" and input ~= "leave" then 
    print("welcome. you have 2 options: play or leave. choose.") 
end 
0

常用的成語是

if input == "play" then 
    print("let's play") 
elseif input == "leave" then 
    print("bye") 
else 
    print("welcome. you have 2 options: play or leave. choose.") 
end 

,但你可能需要一個循環由@luther的建議。