我正在尝试做最简单的事情:
然而,当前代码只会打印第一条消息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
这里有什么问题?感谢任何帮助,谢谢
答案 0 :(得分: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 :(得分:1)
第if input ~= "play" or "leave" then
行评估为:
if (input ~= "play") or "leave" then
字符串"leave"
或任何字符串都被认为是真正的值。
您需要使用and
比较两个字符串:
if input ~= "play" and input ~= "leave" then
print("welcome. you have 2 options: play or leave. choose.")
end
答案 2 :(得分:1)
您需要一个循环,正如您在此处所说的那样,您可以看到此循环,如果输入没有退出,请重做代码,否则else它将检查if,elseif,最后是else
print("welcome. you have 2 options: play or leave. choose.")
while input ~= "exit" do
input = io.read()
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
end
答案 3 :(得分: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建议的循环。