我对LUA中的io.read命令感到震惊。下面的示例跳过文本读取行。只有在之前输入数字时才会发生这种情况。
repeat
print("Input number!")
number=io.read("*n")
print("Would you like do to this again? (y/n)")
again = io.read()
until again == "n"
我在两个IDE(repl和ZeroBrane)中尝试了这个,它让我感觉MAAAD !!!
帮会有人帮忙吗?
干杯,
乌尔里希
答案 0 :(得分:0)
尝试逐行读取字符串,并使用tonumber()
将字符串转换为数字repeat
print("Input number!")
num = tonumber(io.read())
print('Would you like do to this again? (y/n)')
again = io.read()
until again == 'n'
在调试时,我看到第二个io.read正在使用在数字结束后启动的缓冲区。
您的代码有更多打印
repeat
print("Input number!")
-- num = tonumber(io.read())
num = io.read('*n')
print('you entered-> ' .. tostring(num))
print('Would you like do to this again? (y/n)')
again = io.read()
print('your choise from (y/n)-> ' .. again)
until again == 'n'
输出
Input number!
234
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)->
Input number!
234y
you entered-> 234
Would you like do to this again? (y/n)
your choise from (y/n)-> y
Input number!
234234n
you entered-> 234234
Would you like do to this again? (y/n)
your choise from (y/n)-> n
此说明来自 Programming in Lua: 21.1
调用io.read(" * number")从当前输入文件中读取一个数字。这是read返回数字而不是字符串的唯一情况。当您需要从文件中读取许多数字时,缺少中间字符串可以显着提高性能。 *数字选项会跳过数字前的任何空格,并接受数字格式,如-3,+ 5.2,1000和-3.4e-23。如果它在当前文件位置找不到数字(由于格式错误或文件结尾),则返回nil。
请为糟糕的描述道歉。