【问题标题】:io.read is skipped Luaio.read 被跳过 Lua
【发布时间】:2015-08-23 13:00:12
【问题描述】:

我尝试将计算器作为第一份作业。虽然我遇到了io.read 函数的问题。

这是我的代码

io.write("let's try making a calculator in LUA!\n\n")

io.write("First number?\n> ")
firstNum = io.read("*n")

io.write("Second number?\n> ")
secNum = io.read("*n")

io.write("Operator?\n>")
op = io.read()

--rest of code goes here--

它让我输入firstNumsecNum,但一旦它到达op 之一,它就会退出而没有错误。这是输出

➜ lua test.lua 
let's try making a calculator in LUA!!

First number?
> 10
Second number?
> 20
Operator?
>⏎

知道我在这里做错了什么吗?

【问题讨论】:

  • 使用firstNum = tonumber(io.read()) 读取带有数字的行
  • firstnum = io.read( "*n", "*l" )。一个普通的io.read( "*n" ) 在输入缓冲区(包括换行符)中留下尾随空格,因此io.read() 会根据需要选择第二行的其余部分,而不是第三行。

标签: input io lua


【解决方案1】:

原因是,在您按下 ENTER 键之前,会读取一个数字。换行符仍在输入缓冲区中,然后被下面的io.read() 读取。

一种选择是读取op,直到它有效为止。例如,跳过空白字符:

repeat op = io.read() until op:match "%S"

或者,只读取一个标点符号:

repeat op = io.read() until op:match "%p"

【讨论】:

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