Tables: arrays and dictionaries

Lua · Essentials · 12 min

Everything nontrivial in Lua is built from tables, so you need them from day one.

A table is an associative array: any value except nil (and NaN) can be a key. Lua uses tables for arrays, records, sets, objects, modules and namespaces.

Construct one with braces. Positional values get integer keys starting at 1, not 0: {"a", "b"} has t[1] == "a". Named fields {x = 1} are sugar for string keys, and t.x is sugar for t["x"]. Use brackets for any other key: {[10] = "ten", ["my key"] = true}.

Reading a missing key returns nil. Assigning nil deletes the key.

The length operator #t gives the length of the sequence part: it is only well defined when the integer keys are 1..n with no nil holes. For arrays use t[#t + 1] = v or table.insert(t, v) to append, table.remove(t) to pop, table.concat to join strings and table.sort to sort in place.

Tables are reference values: assigning a table to another variable doesn't copy it, and two tables are == only if they are the same table. That makes them cheap to pass around, but you need to copy explicitly when you want an independent value.

Example

local fruits = {"apple", "banana"}
fruits[#fruits + 1] = "cherry"
table.insert(fruits, 1, "kiwi")        -- insert at position 1
print(#fruits, fruits[1])              --> 4	kiwi
print(table.concat(fruits, ", "))      --> kiwi, apple, banana, cherry

local point = {x = 3, y = 4, ["z-axis"] = 0}
point.x = nil                          -- delete a key
print(point.x, point["z-axis"])        --> nil	0

local alias = fruits
alias[1] = "lime"
print(fruits[1])                       --> lime (same table)
print({} == {})                        --> false

table.sort(fruits)
print(table.concat(fruits, " "))       --> apple banana cherry lime
print(table.remove(fruits), #fruits)   --> lime	3

Remember

  • Tables are the only data structure: arrays, maps, objects, modules
  • Arrays start at index 1; t.x means t["x"]
  • #t is reliable only for sequences without nil holes
  • Tables are references, compared by identity

Watch out for

  • Storing nil in the middle of an array, which makes #t and ipairs unreliable.

Check yourself

  1. After t = {10, 20, 30}, what is t[0]?
  2. What does local b = a do when a is a table?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.lua.org/manual/5.4/manual.html#3.4.9