TExcelTAD
Home › Lua › Lua Table Library

Lua Table Library

The table library provides functions for working with tables used as sequences (lists). There are only seven of them, but they cover most everyday list work.

Function Purpose
table.insert(t, v) append v
table.insert(t, pos, v) insert v at pos, shifting the rest up
table.remove(t [, pos]) remove and return the element at pos (default: the last)
table.concat(t [, sep [, i [, j]]]) join strings/numbers into one string
table.sort(t [, comp]) sort in place
table.unpack(t [, i [, j]]) return the elements as separate values
table.pack(...) collect values into a table with field n
table.move(a1, f, e, t [, a2]) copy elements a1[f..e] to a2[t..]

insert and remove

lua · try it yourself
local tasks = { "write", "test" }
table.insert(tasks, "deploy")          -- at the end
table.insert(tasks, 1, "plan")         -- at the front
print(table.concat(tasks, " > "))

local last = table.remove(tasks)       -- pop the last
local first = table.remove(tasks, 1)   -- shift the first
print(last, first)
print(table.concat(tasks, " > "), #tasks)
plan > write > test > deploy
deploy	plan
write > test	2

With insert and remove at the end, a table works as a stack; adding at the end and removing at position 1 makes a queue (fine for small queues: removing at the front shifts every element).

concat

table.concat joins the elements with an optional separator. It is much faster than building a string with .. in a loop. The elements must be strings or numbers:

lua · try it yourself
local words = { "Lua", "is", "fun" }
print(table.concat(words))
print(table.concat(words, " "))
print(table.concat({ 1, 2, 3, 4, 5 }, "+", 2, 4))

local ok, err = pcall(table.concat, { "a", true })
print(err)
Luaisfun
Lua is fun
2+3+4
invalid value (boolean) at index 2 in table for 'concat'

sort

table.sort sorts in place (it changes the table and returns nothing). By default it uses <, so the elements must be all numbers or all strings. Pass a comparison function for other orders:

lua · try it yourself
local nums = { 42, 7, 19, 3, 25 }
table.sort(nums)
print(table.concat(nums, " "))

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

local names = { "bob", "Alice", "carol", "Dave" }
table.sort(names)
print(table.concat(names, " "))
table.sort(names, function(a, b) return a:lower() < b:lower() end)
print(table.concat(names, " "))
3 7 19 25 42
42 25 19 7 3
Alice Dave bob carol
Alice bob carol Dave

Warning: The comparison must be a strict "less than": a < b, never a <= b. An inconsistent comparison can make table.sort raise "invalid order function for sorting". The sort is also not stable: equal elements may be reordered, so add a tie-breaker when that matters.

Sorting records

lua · try it yourself
local cities = {
  { name = "Lagos", pop = 15.4 },
  { name = "Cairo", pop = 22.6 },
  { name = "Lima", pop = 11.3 },
}
table.sort(cities, function(a, b) return a.pop > b.pop end)
for i, c in ipairs(cities) do
  print(i, c.name, c.pop)
end
1	Cairo	22.6
2	Lagos	15.4
3	Lima	11.3

unpack, pack and move

lua · try it yourself
local rgb = { 255, 128, 0 }
print(table.unpack(rgb))
print(string.format("#%02X%02X%02X", table.unpack(rgb)))

local p = table.pack("x", nil, "z")
print(p.n, p[1], p[3])

local src = { "a", "b", "c", "d" }
local dst = table.move(src, 2, 4, 1, {})   -- copy src[2..4] into a new table
print(table.concat(dst, ","))
table.move(src, 1, 3, 2)                   -- shift right inside the same table
print(table.concat(src, ","))
255	128	0
#FF8000
3	x	z
b,c,d
a,a,b,c

table.move returns the destination table, which makes it handy for copying slices.

Test yourself

What does table.remove(t) do with no position?

  1. Removes the first element
  2. Removes the last element and returns it
  3. Empties the table
  4. Raises an error

What does table.sort(t) return?

  1. A sorted copy
  2. The sorted table
  3. Nothing: it sorts t in place
  4. The number of swaps

Why is table.concat(parts) preferred over s = s .. part in a loop?

  1. It sorts the parts
  2. It builds the result once instead of creating many intermediate strings
  3. It works with tables of tables
  4. It adds newlines