24. The table library — Homework solutions

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

Problem 1 — Shopping line

Problem. Print a list of names on one comma-separated line.

Worked solution.

local items = {"milk", "bread", "eggs", "apples"}
print(table.concat(items, ", "))

Output:

milk, bread, eggs, apples

Common mistakes.

  • Building the line by hand with a loop and ... It works, but table.concat is the one-line tool for this.

Problem 2 — High to low

Problem. Sort numbers from highest to lowest, then print them.

How to think about it. Give table.sort a comparator that returns true when the first number is bigger.

Worked solution.

local nums = {30, 12, 7, 24}
table.sort(nums, function(a, b)
    return a > b
end)
print(table.concat(nums, " "))

Output:

30 24 12 7

Common mistakes.

  • Writing return a < b, which gives ascending order. The comparator answers "should a come first?" — for highest-first, a wins when bigger.

Problem 3 — Leaderboard

Problem. Sort names alphabetically and print a numbered list.

How to think about it. table.sort with no comparator sorts text alphabetically. Then walk it with ipairs, printing position and name.

Worked solution.

local players = {"Ben", "Ada", "Cara", "Dan"}
table.sort(players)

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

Output:

1. Ada
2. Ben
3. Cara
4. Dan

Challenge — Top three

Problem. Sort highest-first and print the top three.

How to think about it. Sort descending, then copy positions 1, 2, and 3 into a small list and concat that.

Worked solution.

local scores = {30, 12, 45, 7, 24, 50}
table.sort(scores, function(a, b)
    return a > b
end)

local top = {scores[1], scores[2], scores[3]}
print(table.concat(top, " "))

Output:

50 45 30

Common mistakes.

  • Printing scores[1] .. scores[2] .. scores[3] with no spaces, giving 504530. A small list plus concat with " " keeps the gaps.

Done?

You now have the table library's most useful tools: insert, remove, concat, sort, and unpack. The last chapter of Part 5 — Modules and require — shows how to split a program across files.