08. Comments and notes to yourself — Homework solutions
The .lua solution files are in
exercises/08/homework/solutions/.
Problem 1 — Annotate a program
Problem. Add a header and two why comments without changing the output.
How to think about it. Comments never affect output, so this is pure communication. The header says what the file does; inline comments explain choices a reader might wonder about.
Worked solution.
--[[
Prints a tiny scoreboard line for one player.
Used to check the score formula by eye.
]]
local base = 50 -- everyone starts the round with 50
local bonus = 25 -- reward for a no-damage run
print("Score: " .. (base + bonus))Common mistakes.
-- add base and bonusover the print line just repeats it. Explain why 25 is the bonus, not that it is added.
Problem 2 — Find the bug by commenting out
Problem. Switch off one line so the output is
start then end.
Worked solution.
print("start")
-- print("this line should not be here")
print("end")Common mistakes.
- Deleting the line instead of commenting it. Commenting keeps it in case you want it back.
Problem 3 — Switch off a block
Problem. Use one multi-line comment to switch off the three middle lines.
Worked solution.
print("first")
--[[
print("middle 1")
print("middle 2")
print("middle 3")
]]
print("last")Output:
first
last
Common mistakes.
- Forgetting the closing
]], which switches off the rest of the file,print("last")included.
Challenge — Why, not what
Problem. Replace repeat-the-code comments with useful ones.
How to think about it. For each line, ask "would a reader already know this from the code?" If yes, the comment is noise — cut it or give the reason instead.
Worked solution. Before:
local lives = 3 -- set lives to 3
lives = lives - 1 -- subtract 1 from livesAfter:
local lives = 3 -- standard start; three tries per game
lives = lives - 1 -- player walked into the lavaCommon mistakes.
- Rewording every comment instead of cutting. Sometimes the best comment is none — if the code is clear, silence is fine.
Done?
You can now leave notes that help instead of clutter, and switch code on and off without deleting it. Next is The print toolkit, deeper into showing things on screen.