Skip to content
AgileLogics
5 min read

The Table Library

Prerequisites: Iterating with pairs and ipairs

local list = {"b", "d"}

table.insert(list, "e")        -- append
table.insert(list, 1, "a")     -- insert at position 1
table.insert(list, 3, "c")
print(table.concat(list, ","))

local removed = table.remove(list)       -- remove last
local first = table.remove(list, 1)      -- remove first
print(removed, first)
print(table.concat(list, ","))
a,b,c,d,e
e	a
b,c,d
  • table.insert(t, v) appends; table.insert(t, pos, v) inserts and shifts the rest up.
  • table.remove(t) removes the last element; table.remove(t, pos) removes at a position and shifts down. Both return the removed value.

concat

local parts = {}
for i = 1, 5 do
  parts[#parts + 1] = "item" .. i
end
print(table.concat(parts, ", "))
print(table.concat({1, 2, 3}))
print(table.concat({"a", "b", "c"}, "-", 2, 3))
item1, item2, item3, item4, item5
123
b-c

Collecting pieces in a table and joining once is the fast way to build large strings.

sort

local numbers = {5, 2, 9, 1}
table.sort(numbers)
print(table.concat(numbers, " "))

table.sort(numbers, function(a, b) return a > b end)
print(table.concat(numbers, " "))

local people = {
  {name = "Linus", age = 28},
  {name = "Grace", age = 45},
  {name = "Ada", age = 36},
}
table.sort(people, function(a, b) return a.age < b.age end)
for _, p in ipairs(people) do print(p.name, p.age) end
1 2 5 9
9 5 2 1
Linus	28
Ada	36
Grace	45

table.sort sorts in place. The optional function returns true if a should come before b. The sort isn't stable — equal elements may be reordered.

unpack and pack

local point = {3, 4}
print(table.unpack(point))
print(math.max(table.unpack({4, 9, 2})))

local packed = table.pack("a", nil, "c")
print(packed.n)
3	4
9
3

table.unpack spreads an array into separate values. (In Lua 5.1 and LuaJIT, it's the global unpack.)