Learn/Lua/7. Tables
Lesson 7 of 8
Sign in

Lua, lesson 7

Tables

Lua has exactly one data structure: the table. It's flexible enough to act as a list, a dictionary, a record, and more. You create one with curly braces.

Tables as lists

Two things to notice:

  • Lua lists start at index 1, not 0.
  • # gives the length of a list.

Add items with table.insert, or by assigning to the next free index. Remove the last item with table.remove:

Reading an index that doesn't exist gives nil, not an error. Avoid leaving nil "holes" in the middle of a list, because # is only reliable for lists without gaps.

Looping over a list

ipairs walks a list in order, giving you each index and value:

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Shopping list

Press Ctrl Enter or Check to test your code.

If you don't need the index, name it _ by convention. A numeric for i = 1, #scores works too.

Sorting and joining

table.sort sorts a list in place, smallest first. To sort in a different order, pass a comparison function that says whether a should come before b:

table.concat joins the items of a list into one string, with an optional separator:

There is no built-in max for a table, but math.max accepts many arguments, and table.unpack spreads a list into separate arguments: math.max(table.unpack(nums)).

Tables as dictionaries

A table can use any value as a key, most often strings:

The or idiom gives a default for missing keys, which is perfect for counting:

Looping over a dictionary

pairs visits every key and value, but in no particular order. When the order matters, collect the keys in a list, sort it, and loop over that:

Further reading

  • Lua 5.5 Reference Manual: Table constructors
  • Lua 5.5 Reference Manual: Table manipulation
  • Lua 5.5 Reference Manual: ipairs and pairs

Read whole-number game scores separated by spaces (at least one score). Print:

Sample input:

Sample output:

The starter reads the scores into a table.

Several people added items to a shared shopping list, so the same item can appear more than once. The first line is the number of entries. Each entry line has an item name and a quantity separated by a space. Add up the quantity for each item and print one line per item, <item>: <total>, in alphabetical order.

Sample input:

Sample output:

The starter reads each entry for you (the match call splits the line; you'll learn how it works in the next lesson).

local scores = {70, 85, 92}
print(scores[1])    -- 70
print(#scores)      -- 3
table.insert(scores, 60)          -- append: {70, 85, 92, 60}
scores[#scores + 1] = 75          -- also appends
table.insert(scores, 1, 50)       -- insert at position 1, shifting the rest
local last = table.remove(scores) -- removes and returns the last item
for i, score in ipairs(scores) do
  print(i, score)
end
local nums = {12, 4, 7}
table.sort(nums)                                   -- {4, 7, 12}
table.sort(nums, function(a, b) return a > b end)  -- {12, 7, 4}
print(table.concat(nums, ", "))   -- 12, 7, 4
local stock = {apple = 5, pear = 2}
print(stock["apple"])   -- 5
print(stock.pear)       -- 2  (shortcut for string keys that look like names)
print(stock.kiwi)       -- nil (missing keys are nil)

stock.kiwi = 7          -- add a key
stock.pear = nil        -- remove a key
stock.plum = (stock.plum or 0) + 3
local keys = {}
for key in pairs(stock) do
  table.insert(keys, key)
end
table.sort(keys)
for _, key in ipairs(keys) do
  print(key .. ": " .. stock[key])
end
Count: <how many>
Highest: <max>
Lowest: <min>
Sorted: <scores from low to high, separated by spaces>
70 92 85 64
Count: 4
Highest: 92
Lowest: 64
Sorted: 64 70 85 92
4
milk 2
eggs 12
milk 1
bread 1
bread: 1
eggs: 12
milk: 3