23. Tables as dictionaries — Homework solutions

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

Problem 1 — Player record

Problem. Build a player table; print each field with pairs.

How to think about it. A literal with the four keys, a for k, v in pairs(...) loop, one print per pair.

Worked solution.

local player = {
    name = "Keiko",
    class = "Mage",
    level = 7,
    alive = true,
}

for key, value in pairs(player) do
    print(key, value)
end

The print order depends on Lua's hashing, so it won't always match the order you wrote.

Common mistakes.

  • Quoting the keys inside the literal: {"name" = "Keiko"}. Inside {}, named keys go without quotes. The bracket form {["name"] = "Keiko"} also works, but bracketless is usual.

Problem 2 — Inventory weights

Problem. Sum the values in a dictionary.

How to think about it. Use pairs, since the keys are strings. Keep a running total like in chapter 22.

Worked solution.

local inventory = {
    sword = 3.5,
    shield = 5.0,
    potion = 0.2,
    map = 0.1,
    coins = 0.05,
}

local total = 0
for _, weight in pairs(inventory) do
    total = total + weight
end

print(string.format("Total weight: %.2f", total))

The _ ignores the key; the sum only needs the values.

Common mistakes.

  • Using ipairs. It only walks numeric keys 1, 2, 3, ..., so for a dictionary it walks nothing.

Problem 3 — Safe lookup

Problem. lookup(dict, key) returns the value or "(not found)".

How to think about it. Look up dict[key]. Return it if it isn't nil; otherwise return the placeholder string.

Worked solution.

local function lookup(dict, key)
    local value = dict[key]
    if value == nil then
        return "(not found)"
    end
    return value
end

local player = { name = "Keiko", level = 7 }

print(lookup(player, "name"))     -- Keiko
print(lookup(player, "email"))    -- (not found)

local key = "level"
print(lookup(player, key))         -- 7

It works for any key — strings ("name"), a variable (key), or even numbers if the dict has numeric keys.

Common mistakes.

  • Using if dict[key] then ... else ... end and forgetting that false is falsy. A dict storing someKey = false would be wrongly reported as "not found". The value == nil check avoids that.

Challenge — Word frequency

Problem. Count occurrences of each word in a list.

How to think about it. Walk the list once. For each word, look it up in counts; if it isn't there yet, treat the count as 0, then add 1 and store it back.

The Lua idiom for zero or current value is (counts[word] or 0). or returns the left side if truthy, else the right, so a nil counts[word] gives 0.

Worked solution.

local words = {"apple", "banana", "apple", "cherry", "apple", "banana"}

local counts = {}
for _, word in ipairs(words) do
    counts[word] = (counts[word] or 0) + 1
end

for word, count in pairs(counts) do
    print(word, count)
end

Output (order may vary):

apple    3
banana   2
cherry   1

Common mistakes.

  • Writing counts[word] = counts[word] + 1 without the or 0. The first time a word is seen, counts[word] is nil, and nil + 1 errors.

Done?

Next, The table library gives you ready-made tools for sorting and joining lists, and the last chapter of Part 5 splits code across files using modules. After that, the Part 5 mini-project — a Text Adventure — combines tables, functions, and modules into a tiny game.