我试着把计算器作为一个很好的第一个任务.虽然我遇到了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
这是我的代码
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()读取.一种选择是读取操作直到它有效.例如,要跳过空格字符:
repeat op = io.read() until op:match "%S"
或者,只读一个标点字符:
repeat op = io.read() until op:match "%p"