Reputation: 163
I tried to make a calculator as a good first assignment. Though I'm having an issue the io.read
function.
Here's my code
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--
It lets me input firstNum
and secNum
, but once it reaches the op
one it just quits with no error. Here's the output
➜ lua test.lua
let's try making a calculator in LUA!!
First number?
> 10
Second number?
> 20
Operator?
>⏎
Any idea what I'm doing wrong here?
Upvotes: 4
Views: 1543
Reputation: 122383
The cause is, a number is read until you press the ENTER key. The newline character is still in the input buffer, and is then read by the following io.read()
.
One option is to read op
until it's valid. For example, to skip whitespace characters:
repeat op = io.read() until op:match "%S"
or, to read only one punctuation character:
repeat op = io.read() until op:match "%p"
Upvotes: 3