input - io.read 被跳过 Lua

标签 input io lua

我尝试制作一个计算器作为第一个作业。虽然我在 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?
>⏎

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

最佳答案

原因是,直到您按 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/

相关文章:

javascript - 如何将文本从 html 输入推送到 AngularJS 数组?

javascript - 在提交时在新选项卡中打开表单点击

input - Mahout - 如何为朴素贝叶斯分类格式化我的输入

windows - 我如何开始编写 Windows minifilter 驱动程序?

c++ - Lua + SWIG 猴子补丁

c++ - 按值传递不调用移动构造函数

jquery - 使用jquery过滤输入文本字段导致光标在IE和Chrome中跳转

vb.net - 异步 PDF 创建的 IOException 问题

Java:读取文件然后将数据写入文本文件

linux - 如何在 Nginx 配置中使用操作系统环境变量?