Skip to content
AgileLogics
5 min read

Tables: The One Data Structure

Prerequisites: Numeric for loops

The table is Lua's only built-in data structure — and it's enough for arrays, dictionaries, sets, records, objects, and modules.

A table maps keys to values. Keys can be any value except nil (usually numbers or strings):

local t = {}
t[1] = "first"
t["color"] = "red"
t.size = 10
t[true] = "yes"

print(t[1])
print(t.color)
print(t["size"])
print(t[true])
print(t.missing)
first
red
10
yes
nil
  • t.name is shorthand for t["name"] (for keys that are valid names).
  • Missing keys give nil; assigning nil removes a key.

Constructors

local list = {"a", "b", "c"}                 -- array: keys 1, 2, 3
local user = {name = "Ada", age = 36}         -- record
local mixed = {"x", "y", count = 2, [10] = "ten", ["with space"] = true}

print(list[1], list[3])
print(user.name, user.age)
print(mixed[2], mixed.count, mixed[10], mixed["with space"])
a	c
Ada	36
y	2	ten	true

Tables are references

A variable holds a reference to a table, not a copy:

local a = {score = 1}
local b = a
b.score = 99
print(a.score)
print(a == b)

local function reset(t)
  t.score = 0
end
reset(a)
print(b.score)
99
true
0

Passing a table to a function lets the function change it. To copy a table, create a new one and copy the fields (the Advanced Tables lesson shows how).