Reading Input with io.read
A program often needs data from outside, like a name or a number. This data is called input. In this course, each exercise gives your program its input as lines of text. Your program reads them with io.read.
Reading a line
io.read() reads the next line of input and returns it as a string. If the input is Alice, this program prints a greeting:
local name = io.read()
print("Hello, " .. name .. "!")
Output:
Hello, Alice!
Each call to io.read() reads one more line.
Turning text into a number
io.read() always returns text, even when the line contains only digits. To do math with it, turn the text into a number with tonumber. If the input is 30:
local text = io.read()
local age = tonumber(text)
print(age + 1)
Output:
31
When the text is not a number, tonumber gives nil. Here the input is thirty:
local age = tonumber(io.read())
print(age)
print(age + 1)
Output:
nil
/usr/bin/lua5.4: main.lua:3: attempt to perform arithmetic on a nil value (local 'age')
age is nil, so age + 1 stops the program with an error. If you see this error, check that the input really was a number.
Reading a number directly
io.read("n") reads a number instead of a line. It skips spaces and line breaks before the number. If the input is 3 4:
local a = io.read("n")
local b = io.read("n")
print(a + b)
Output:
7
Like tonumber, it gives nil when the input is not a number.
There is one trap. io.read("n") stops right after the number. It does not read the rest of that line. So a plain io.read() after it reads what is left of the line, which is often nothing. Here the input is 30 and then Alice:
local age = io.read("n")
local name = io.read()
print("[" .. name .. "]")
Output:
[]
name is an empty string, not Alice. The simple fix is to read lines first and numbers after them.
In the exercise, read a name and then an age, and print a greeting.