28. Many objects together — Homework solutions

Solution files are in exercises/28/homework/solutions/. All four use the same small Hero class from each starter file's top.

Problem 1 — A party of heroes

Problem. Build a list of three heroes and print each one.

Worked solution.

local party = {
    Hero.new("Ada", 100),
    Hero.new("Ben", 80),
    Hero.new("Cara", 120),
}

for _, h in ipairs(party) do
    print(h.name .. ": " .. h.hp .. " HP")
end

Output:

Ada: 100 HP
Ben: 80 HP
Cara: 120 HP

Problem 2 — Total HP

Problem. Add up everyone's HP.

Worked solution.

local total = 0
for _, h in ipairs(party) do
    total = total + h.hp
end
print("Team HP: " .. total)   -- Team HP: 300

The accumulate pattern from Chapter 20, reading a field instead of a plain number.

Problem 3 — Who is hurt?

Problem. Print every hero whose hp is below their max_hp.

Worked solution.

for _, h in ipairs(party) do
    if h.hp < h.max_hp then
        print(h.name .. " is hurt.")
    end
end

Only heroes who took damage print. The if compares two fields of the same object.

Challenge — Strongest hero

Problem. Find the hero with the most HP.

How to think about it. Accumulate a maximum: keep a variable for the best hero so far, replacing it whenever a stronger one appears. Start it as the first hero (or nil, filled on the first turn).

Worked solution.

local strongest = party[1]
for _, h in ipairs(party) do
    if h.hp > strongest.hp then
        strongest = h
    end
end
print("Strongest: " .. strongest.name)   -- Strongest: Cara

Common mistakes.

  • Starting strongest at nil, then writing h.hp > strongest.hp on the first turn reads nil.hp and errors. Start with the first hero, or guard the first turn.

Done?

You can now manage a whole collection of objects with loops you already know. Next, Inheritance in depth lets one class build on another, so shared behaviour is written once.