09. The print toolkit — Homework solutions

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

Problem 1 — A stat row

Problem. Print three values on one line, comma-separated.

Worked solution.

print("Keiko", 7, 95)

Output (tabs between the values):

Keiko   7       95

Common mistakes.

  • Quoting the numbers. 7 and "7" look alike but are different types; the problem wants numbers.

Problem 2 — A polished line

Problem. Build one exact sentence with ...

How to think about it. Glue text and variables in order, with spaces inside the string pieces.

Worked solution.

local name = "Keiko"
local hp = 95
local level = 7

print(name .. " has " .. hp .. " HP at level " .. level)

Output:

Keiko has 95 HP at level 7

Common mistakes.

  • Forgetting spaces inside the quotes, giving Keikohas95HP. .. adds no spacing; you add every space yourself.

Problem 3 — Spaced out

Problem. Three lines, a blank line between each, five print calls.

Worked solution.

print("Line one")
print()
print("Line two")
print()
print("Line three")

Common mistakes.

  • Writing print(" ") (a space) instead of print() (nothing). Both look blank, but print() says "empty line" plainly.

Challenge — Receipt

Problem. Print a small receipt: item lines, a blank line, then a total.

Worked solution.

local apple = 3
local bread = 2
local milk = 4
local total = apple + bread + milk

print("apple: " .. apple)
print("bread: " .. bread)
print("milk: " .. milk)
print()
print("Total: " .. total)

Output:

apple: 3
bread: 2
milk: 4

Total: 9

Common mistakes.

  • Typing the total as a literal 9 instead of computing it. A computed total updates when a price changes; a typed one won't.

Done?

You can now show values exactly how you want. The last chapter of this part — Reading error messages — covers the red text Lua prints when something breaks.