Lua中的If语句

我正在尝试做最简单的事情:

  • 程序打印第一条消息并等待用户输入
  • 用户输入"play"或"leave"
  • 如果用户输入"play",程序打印"let's play"并退出(暂时)
  • 如果用户输入"leave",程序打印"bye"并退出
  • 如果用户输入的不是"play"或"leave",程序打印第一条消息并等待用户输入

然而当前的代码只打印第一条消息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

这里有什么问题吗?任何帮助都将不胜感激,谢谢

点赞
用户2505965
用户2505965

代码行 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
2017-10-08 19:26:00
用户3574628
用户3574628

if语句只会执行一次,它不会跳转到程序的其他部分。要实现这个目的,你需要将你的输入代码放在一个while循环中,并在获得有效响应时跳出循环:

while true do
  print("欢迎。你有两个选项:玩或离开。请选择。")
  local input = io.read()

  if input == "play" then
    print("让我们开始游戏")
    break
  elseif input == "leave" then
    print("再见")
    break
  end

end

这里阅读更多关于循环的内容。

2017-10-08 19:27:28
用户107090
用户107090

通常的写法是:

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 的建议,你可能需要用到循环。

2017-10-08 20:00:06
用户10212962
用户10212962

你需要一个循环,如你所见,这个 while 语句的意思是,如果输入不是“exit”,重新执行代码,而 else 语句则表示它将检查 if、elseif,最后是 else。

print("欢迎。你有 2 个选项:玩游戏或者离开。请选择。")

while input ~= "exit" do
     input = io.read()
     if input == "play" then
         print("让我们玩游戏吧")
     elseif input == "leave" then
         print("再见")
     else
         print("欢迎。你有 2 个选项:玩游戏或者离开。请选择。")
     end
end
2018-08-11 17:17:52