如果在Lua
问题描述:
声明
我试图做简单的事情:如果在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值:所理解的任何帮助,感谢
答
的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。
答
线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
答
常用的成语是
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的建议。
什么是“输入”? – hjpotter92
我编辑过的代码是:input = io.read()。问题在于在任何用户输入程序之后再打印第一条消息并退出 – hexbreak