15. Getting input — Homework solutions

The .lua solution files are in exercises/15/homework/solutions/.

Problem 1 — Greet by name

Problem. Prompt with io.write, read with io.read, greet with an exclamation mark.

How to think about it. Three lines: write the prompt, read the answer, print the greeting. The exclamation mark goes inside the string, after the variable.

Worked solution.

io.write("First name: ")
local name = io.read()
print("Hello, " .. name .. "!")

Common mistakes.

  • Forgetting the trailing space. "First name:" jams the cursor against the colon; "First name: " is the standard.

Problem 2 — Sum of two

Problem. Read two numbers; print a + b = c.

How to think about it. Two prompts, two reads, each wrapped in tonumber. Build the output from the three numbers with ...

Worked solution.

io.write("First number:  ")
local a = tonumber(io.read())
io.write("Second number: ")
local b = tonumber(io.read())

local c = a + b
print(a .. " + " .. b .. " = " .. c)

Common mistakes.

  • Skipping tonumber. The values stay strings, so a + b fails with attempt to perform arithmetic on a string value.
  • Wrapping tonumber around the prompt, not the answer. tonumber("First number: ") is nil, so the bug shows up a line later.

Problem 3 — Years to retirement

Problem. Compute 65 - age and print a labelled sentence.

How to think about it. Prompt, read, subtract, print. Mind the order: 65 - age, not age - 65.

Worked solution.

io.write("Your current age: ")
local age = tonumber(io.read())

local years_left = 65 - age
print("You have " .. years_left .. " years until retirement.")

Common mistakes.

  • Doing age - 65, which prints a negative for everyone under 65. Subtraction is not commutative — order matters.

Challenge — BMI

Problem. Prompt for height and weight (decimals), compute BMI, print it to one decimal place.

How to think about it. Two prompts, two reads, both through tonumber. weight / (height * height) gives a float; string.format("%.1f", bmi) shows one digit after the decimal.

Worked solution.

io.write("Height in metres (e.g. 1.78): ")
local height = tonumber(io.read())
io.write("Weight in kg (e.g. 72.5):     ")
local weight = tonumber(io.read())

local bmi = weight / (height * height)

print(string.format("BMI: %.1f", bmi))

Common mistakes.

  • Forgetting the parentheses in height * height. Without them, weight / height * height runs left to right: divide by height, then multiply by it again — the heights cancel and you get weight back.
  • Entering height in centimetres (like 178) instead of metres (1.78). BMI uses metres, as the starter prompt says.

Done?

Every Part 3 chapter is done. The mini-project — the Character Sheet — uses everything from chapters 11 to 15.