24. The table library

You have built tables by hand and walked them with ipairs and pairs. Lua also ships a small table library — ready-made functions for the list jobs you do over and over: adding, removing, joining into a string, and sorting. Learn these four and you never have to reinvent them.

This chapter uses the list shape of tables from Chapter 22.

Adding and removing (a recap)

You met these in Chapter 22; here they are together.

local items = {"sword", "shield"}

table.insert(items, "potion")     -- add to the end
table.insert(items, 1, "torch")   -- insert at position 1
table.remove(items, 2)            -- remove position 2
table.remove(items)               -- remove the last one

These shuffle the other items along so the list stays gap-free — which is why you use them instead of setting slots to nil yourself.

Joining a list into text: table.concat

table.concat(list, separator) glues every item into one string, the separator between each. Items must be strings or numbers.

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

Much tidier than building the string with a loop and ... To display a list on one line, reach for concat.

Open exercises/24/01-concat.lua. A list of numbers is provided. Print them on one line separated by " + ", then print it again separated by spaces.

Sorting a list: table.sort

table.sort(list) reorders the list in place into ascending order. It changes the original rather than returning a new one.

local scores = {30, 12, 7, 24}
table.sort(scores)
print(table.concat(scores, " "))   -- 7 12 24 30

It sorts text alphabetically too:

local names = {"Cara", "Ada", "Ben"}
table.sort(names)
print(table.concat(names, ", "))   -- Ada, Ben, Cara

Sorting your own way

To sort differently, hand table.sort a function that takes two items and returns true when the first should come before the second. For descending order, "before" means "bigger":

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

That little function is a comparator. You write it once, inline, and table.sort calls it as often as it needs — your first taste of passing a function into another, a powerful idea you will meet again.

Spreading a list: table.unpack

table.unpack(list) turns a list back into separate values — the mirror image of the multi-assignment you saw in Chapter 11:

local point = {3, 4}
local x, y = table.unpack(point)
print(x, y)        -- 3   4

It is also handy for feeding a list to a function that expects separate arguments:

local nums = {5, 9, 2}
print(math.max(table.unpack(nums)))   -- 9

Homework

Homework files are in exercises/24/homework/.

Problem 1 — Shopping line

Open exercises/24/homework/01-shopping-line.lua. A list of item names is provided. Print it as one line separated by commas, using table.concat.

Problem 2 — High to low

Open exercises/24/homework/02-high-to-low.lua. A list of numbers is provided. Sort it highest to lowest with a comparator, then print it with table.concat.

Problem 3 — Leaderboard

Open exercises/24/homework/03-leaderboard.lua. A jumbled list of player names is provided. Sort them alphabetically and print a numbered leaderboard, one per line (1. Ada, 2. Ben, ...).

Challenge — Top three

Open exercises/24/homework/04-top-three.lua. A list of scores is provided. Sort it highest-first, then print only the top three on one line separated by " ". Use table.sort and table.concat, plus a small loop or slice to take just the first three.

Stuck or finished? Open the homework solutions page.