我尝试制作一个计算器作为第一个作业。虽然我在 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--
它允许我输入 firstNum
和 secNum
,但是一旦到达 op
,它就会退出,没有错误。这是输出
➜ lua test.lua
let's try making a calculator in LUA!!
First number?
> 10
Second number?
> 20
Operator?
>⏎
知道我在这里做错了什么吗?
最佳答案
原因是,直到您按 ENTER 键才会读取数字。换行符仍在输入缓冲区中,然后由以下 io.read() 读取。
一种选择是读取op
直到它有效。例如,要跳过空白字符:
repeat op = io.read() until op:match "%S"
或者,仅读取一个标点符号:
repeat op = io.read() until op:match "%p"
关于input - io.read 被跳过 Lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30719687/