Io.read skipped by Lua

I tried to make the calculator a good good destination. Although I have a problem with the function io.read.

Here is my code

io.write("let 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--

It allows me to type firstNumand secNum, but as soon as it reaches op, it just quits without errors. Here is the conclusion

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

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

Any idea what I'm doing wrong here?

+4
source share
1 answer

The reason is that the number is read until you press the key ENTER. A newline is still in the input buffer and then reads next io.read().

One option is to read opuntil it is valid. For example, to skip whitespace:

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

or to read only one punctuation mark:

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

All Articles