Lua User Input
User input is text that a program reads from the person running it. Lua reads one typed line at a time with io.read().
Read a name and greet it
This run is shown with the sample answer Maya, typed on one line. The name comes back as a string, ready to join into a greeting.
local name = io.read()
print("Hello, " .. name .. "!")tonumber makes typed digits add up
This run is shown with the sample answers 7 and 5, one on each line. Joining the raw strings would give 75, so a printed 12 proves both were converted.
local a = tonumber(io.read())
local b = tonumber(io.read())
print(a + b)Read an age and add a year
This run is shown with the sample answer 20. The converted age can go straight into arithmetic.
local age = tonumber(io.read())
print(age + 1)Example
local name = io.read()
local city = io.read()
print("Summary")
print("Name: " .. name)
print("City: " .. city)Key points
- io.read(): reads one line the user types and returns it as a string.
- Enter key: pressing Enter ends the line that io.read() returns.
- String result: even typed digits come back as text, not as a number.
- tonumber(): turns a numeric string into a number.
- Bad text: tonumber() returns nil when the string is not a number.
In this example, the program asks two questions and is shown with the sample answers Maya and Austin, one typed on each line. It stores both lines as strings. It then prints a short summary card built from those two stored answers.
Note
checking a tonumber() result for nil catches bad input before any maths uses it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does tonumber("abc") return?