10. Reading error messages — Homework solutions

The .lua solution files are in exercises/10/homework/solutions/. These problems practise the loop: run, read the first error, fix one thing, run again.

Problem 1 — Name the error

Problem. Identify the error type, then fix it.

How to think about it. Run the file, read the message, and match it to one of the four types: unfinished string, call a nil value, concatenate a nil value, or 'end' expected.

Worked solution. The starter line is:

print("Hello, " .. player_name)

with no player_name defined. The error is attempt to concatenate a nil value — the variable has no value, so it is nil. A fix:

local player_name = "Keiko"
print("Hello, " .. player_name)
-- error type: attempt to concatenate a nil value

Problem 2 — Fix the quote

Problem. Repair an unfinished string.

Worked solution.

print("A wizard is never late.")

The only change is the missing closing " before the ).

Common mistakes.

  • Adding the quote after the ). The closing quote goes at the end of the text, before the closing parenthesis.

Problem 3 — Fix the typo

Problem. A misspelled function name causes "attempt to call a nil value".

Worked solution. The starter has prnt("Fixed!"). The message names the culprit: (global 'prnt'). Fix the spelling:

print("Fixed!")

Common mistakes.

  • "Fixing" it by inventing a different name. Lua only knows the names it knows. When the message says 'prnt', the fix is almost always the real function spelled correctly — print.

Challenge — Three in a row

Problem. Three mistakes, one of each kind, fixed one at a time.

How to think about it. Run. The first error is the unfinished string or the misspelled print, whichever comes first. Fix it. Run again — the next error shows. Fix it. Run again for the missing end. The loop, working as intended.

Worked solution.

print("Starting up")
print("Working")
if true then
    print("done")
end

The starter had a missing closing quote on line one, prnt on line two, and an if with no end. Fixed in three passes, it prints:

Starting up
Working
done

Common mistakes.

  • Fixing all three at once and losing track of which change did what. One error, one fix, run again — even when you think you see them all.

Done?

That is the end of Part 2. You can install and run Lua, print exactly what you want, comment your code, and read Lua's errors. The Part 2 mini-project — the ASCII Name Banner — puts your print skills to work building a picture out of text. Then Part 3 digs into variables, strings, numbers, and input.