22. Tables as lists — Homework solutions

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

Problem 1 — Favourite games

Problem. Print a numbered list using ipairs.

How to think about it. ipairs gives you the index and the value. Build each line from the index, a dot, a space, and the value.

Worked solution.

local games = {"Roblox", "Minecraft", "Terraria", "Stardew Valley", "Hades"}

for i, name in ipairs(games) do
    print(i .. ". " .. name)
end

Output:

1. Roblox
2. Minecraft
3. Terraria
4. Stardew Valley
5. Hades

Common mistakes.

  • Indexing from 0: for i = 0, #games do print(games[i]) end. The first pass prints nil; position 0 has no value.
  • Using pairs instead of ipairs. Both work on a list, but pairs does not guarantee order, so prefer ipairs.

Problem 2 — Sum the list

Problem. Add every number in a list; print the total.

How to think about it. Keep a running total, updated with total = total + value inside the loop. With ipairs you do not need the index.

Worked solution.

local scores = {12, 7, 24, 9, 30}

local total = 0
for _, value in ipairs(scores) do
    total = total + value
end

print("Total: " .. total)

The _ is a conventional name for I do not care about this value. It is an ordinary variable with no special meaning to Lua, just a reader hint.

Common mistakes.

  • Forgetting total = 0 before the loop. nil + 12 is an error.

Problem 3 — Insert and remove

Problem. Do four list operations, printing the list after each.

How to think about it. Write a tiny printing routine once and call it after each step (a function, like chapter 21 introduced). Then the operations are one-liners.

Worked solution.

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

local function show(label)
    io.write(label .. ": ")
    for i, v in ipairs(list) do
        io.write(v)
        if i < #list then io.write(", ") end
    end
    print()
end

show("Start          ")
table.insert(list, "date")
show("After append   ")
table.insert(list, 1, "apricot")
show("After insert@1 ")
table.remove(list)
show("After remove   ")
table.remove(list, 2)
show("After remove@2 ")

A trimmed sample of the output:

Start          : apple, banana, cherry
After append   : apple, banana, cherry, date
After insert@1 : apricot, apple, banana, cherry, date
After remove   : apricot, apple, banana, cherry
After remove@2 : apricot, banana, cherry

Common mistakes.

  • Setting list[2] = nil instead of table.remove(list, 2). That leaves a hole at position 2 and breaks ipairs.

Challenge — Reverse a list

Problem. reverse(list) returns a new list, original unchanged.

How to think about it. Build a new table inside the function. Walk the original from last to first (a for counting backwards), append each value to the new table, and return it.

Worked solution.

local function reverse(list)
    local result = {}
    for i = #list, 1, -1 do
        table.insert(result, list[i])
    end
    return result
end

local fruits = {"apple", "banana", "cherry"}
print(table.concat(fruits, ", "))            -- apple, banana, cherry

local reversed = reverse(fruits)
print(table.concat(reversed, ", "))          -- cherry, banana, apple
print(table.concat(fruits, ", "))            -- apple, banana, cherry (unchanged)

table.concat(list, sep) joins a list of strings with a separator. No chapter covered it, but it is the natural tool for displaying a list as one line.

Common mistakes.

  • Modifying list in place instead of building a new table. The problem says the original must stay unchanged.
  • Looping with for i = 1, #list do and assigning to result[i]. That builds result in the original order, not reversed. The step -1 is the trick.

Done?

The next chapter teaches the other way to use tables — as dictionaries with named keys. The two shapes can share one table.