我有什么办法可以解决此if语句?

时间:2020-10-01 13:36:37

标签: lua

我对使用Lua进行编码相对较新,但是我对Python有一些经验。我想尝试一些不同的方法,其中将随机数滚动,而您必须尝试猜测该数字是多少。如果您做对了,程序就会结束,那就是在我的空闲时间进行一些简单的工作。但是,我遇到了Lua的问题,第16行的if语句不起作用。

print("Test")
print("--------------------------------------")

game = 1

x = math.random(1,6)

while game == 1 do
  x = math.random(1,6)
  io.write("Enter a number. If you roll that number on the dice you win: ")
  user_input = io.read()
  print(" ")
  print("You chose " .. user_input)
  print(" ")
  print(x)
  if user_input == x then -------------> this line doesn't work
    print(" ")
    print("You rolled the number you chose.")
    game = 2
  else
    print(" ")
    print("You did not roll the random number.")
    print("--------------------------------------")
  end
end

2 个答案:

答案 0 :(得分:2)

似乎您正在从控制台获取输入并将其存储为字符串。您当前正在将字符串与整数进行比较。这意味着您将永远以错误告终。在这里,我更改了代码,使其以整数而不是字符串的形式输入,以便该语句现在可以使用。

 print("Test")
 print("--------------------------------------")

 game = 1

 x = math.random(1,6)

 while game == 1 do
   x = math.random(1,6)
   io.write("Enter a number. If you roll that number on the dice you win: ")
   user_input = io.read("*number")
   print(" ")
   print("You chose " .. user_input)
   print(" ")
   print(x)
   if user_input == x then
     print(" ")
     print("You rolled the number you chose.")
     game = 2
   else
     print(" ")
     print("You did not roll the random number.")
     print("--------------------------------------")
   end
 end

答案 1 :(得分:0)

if user_input == x then替换为if tonumber( user_input ) == x then。对您来说显而易见的是,user_input是一个字符串,而x是一个数字;并且在Lua中没有隐式类型转换。

奖金:

  • 如果唯一的参数是字符串或表格,则可以在函数调用中添加括号:f("a")f'a'
  • 要结束循环,您可以简单地使用break,完全摆脱game变量(使用while ( true )),
  • 在没有特殊原因之前,始终将变量声明为local。在您的示例中,这适用于xuser_input,如果不是多余的,则适用于game
  • Lua具有HereDoc语法,因此您可以替换:
    print(" ")
    print("You did not roll the random number.")
    print("--------------------------------------")

使用

    print [[

You did not roll the random number.
--------------------------------------
]]