Reputation: 11
I tried to write some simple code for mathematical equations, reading console input. Here's my minimal executable example:
print("Please enter a number")
local number = io.read("*n")
print("You entered the number: " .. number)
print("Please enter 'yes'")
local word = io.read("*l")
if word == "yes" then
print("Thank you!")
else
print(":(")
end
I entered 1
, pressed return, then entered yes
and pressed return, but I always get the following output in the Lua console:
Please enter a number
>> 1
You entered the number: 1
Please enter 'yes'
:(
I don't understand why I cannot even enter yes
. The program just terminates.
How can I fix that?
Upvotes: 0
Views: 458
Reputation: 28964
As pointed out by Egor io.read("*n")
will read a numeral without the linefeed after that number.
So if you enter 1
and read that with io.read("*n")
, you will actually leave an empty line in the input stream.
Once you read a new line with io.read("*l")
Lua will read that empty line from the stream. Therefor it does not wait for your input, but evaluates the content of word
immediately.
As word
is an empty string word == "yes"
is false
.
You can fix that by using io.read("*n", "*l")
for reading the numeral and the following emtpy line. That way the input stream is empty when you call io.read("*l") next and Lua will wait for you to enter your word.
You can do run this code:
print("Enter 1")
local number, newLine = io.read("*n", "*L")
print(number == 1)
print(newLine == "\n")
To see that your number is indeed followed by a "\n"
Upvotes: 1