【问题标题】:LUA: Reading text after reading number does not workLUA:读取数字后读取文本不起作用
【发布时间】:2018-06-01 23:00:43
【问题描述】:

我对 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 !!!

有人可以帮忙吗?

干杯,

乌尔里希

【问题讨论】:

  • 试试number=io.read("*n", "*l")
  • 不! Line-Parameter 无论如何都是默认的,然后你就需要更多的等待返回!
  • “更多等待返回”是什么意思? @EgorSkriptunoff 提出的解决方案非常适合您问题中的示例。

标签: text lua numbers


【解决方案1】:

尝试逐行读取字符串并使用 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 返回数字而不是字符串的唯一情况。当您需要从文件中读取许多数字时,没有中间字符串可以显着提高性能。 *number 选项会跳过数字前的所有空格,并接受 -3、+5.2、1000 和 -3.4e-23 等数字格式。如果在当前文件位置找不到数字(由于格式错误或文件结尾),则返回 nil。

请为糟糕的描述道歉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多