Input 从Lua控制台读取数字后,如何读取单词?

Input 从Lua控制台读取数字后,如何读取单词?,input,lua,Input,Lua,我试图为数学方程编写一些简单的代码,阅读控制台输入。下面是我的最小可执行示例: print("Please enter a number") local number = io.read("*n") print("You entered the number: " .. number) print("Please enter 'yes'") local word = io.read("*l") if word == "yes" then print("Thank you!") else

我试图为数学方程编写一些简单的代码,阅读控制台输入。下面是我的最小可执行示例:

print("Please enter a number")
local number = io.read("*n")
print("You entered the number: " .. number)
print("Please enter 'yes'")
local word = io.read("*l")
if word == "yes" then
  print("Thank you!")
else
  print(":(")
end
我输入了
1
,按下了return,然后输入了
yes
并按下了return,但我总是在Lua控制台中获得以下输出:

 Please enter a number
 >> 1
 You entered the number: 1
 Please enter 'yes'
 :(
我不明白为什么我甚至不能输入
yes
。程序刚刚终止。
如何解决这个问题?

正如Egor
io所指出的。read(“*n”)
将读取一个数字,但该数字后面没有换行符

因此,如果您输入
1
并使用
io.read(“*n”)
读取该值,您实际上会在输入流中留下一个空行

一旦您使用io读取新行,read(“*l”)Lua将从流中读取该空行。因此,它不会等待您的输入,而是立即计算
word
的内容

因为
word
是一个空字符串
word==“yes”
false

您可以通过使用
io.read(“*n”和“*l”)
读取数字和下面的emtpy行来解决这个问题。这样,当您接下来调用io.read(“*l”)时,输入流是空的,Lua将等待您输入单词

您可以运行以下代码:

print("Enter 1")
local number, newLine = io.read("*n", "*L")
print(number == 1)
print(newLine == "\n")

在Lua中,要看到您的数字后面确实跟有一个
“\n”

读取数字有点违反直觉(它读取的数字后面没有LF)。将所有
io.read(“*n”)
替换为
io.read(“*n”,“*l”)
,以修复它