Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 32 ยท Tables

The table Library

Learn the Lua table library: table.insert, remove, concat, sort with a comparator, unpack and move, plus why table.sort is not stable. Runnable JavaScript stand-ins.

Tables hold your data, but Lua keeps the language tiny, so most list operations live in a standard library called table. Its functions work on sequences: tables whose keys run 1, 2, 3, and so on with no gaps (see Tables as Arrays and Dictionaries). Learning six functions covers nearly everything you do with lists.

Because real Lua cannot run on this site, the Lua snippets are read-only and the live editors are JavaScript stand-ins that follow the same rules. Where a result is quoted from Lua, it describes what Lua 5.4 does.

The six workhorses

insert Add at the end or at a position.
remove Take out and close the gap.
concat Join strings with a separator.

Edit a list, then join it.

1 / 2

table.insert and table.remove

table.insert(t, value) appends at position #t + 1. With three arguments, table.insert(t, pos, value) puts the value at pos and shifts the later items up:

LUA
local fruits = {"apple", "cherry"}
table.insert(fruits, "date")          -- {"apple", "cherry", "date"}
table.insert(fruits, 2, "banana")     -- {"apple", "banana", "cherry", "date"}

table.remove(t, pos) removes the item at pos, shifts later items down to close the gap, and returns the removed value. Without pos it removes the last item. On an empty table it returns nil:

LUA
local last = table.remove(fruits)      --> "date"
local first = table.remove(fruits, 1)  --> "apple"

Inserting or removing near the front moves every later item, so it costs time proportional to the list size. That is fine for small lists; for queues with many items see Tables in Practice.

JS Stand-in: insert and remove on a 1-based list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

table.concat

table.concat(t, sep, i, j) joins the items from i to j (defaults: 1 and #t) into one string, putting sep between them (default: empty). Every item must be a string or a number; a boolean, a table or a nil raises an error.

LUA
local words = {"Lua", "is", "small"}
print(table.concat(words, " "))        --> Lua is small
print(table.concat({1, 2, 3}, ", "))   --> 1, 2, 3
print(table.concat(words, "-", 2, 3))  --> is-small

This is also the efficient way to build a long string piece by piece. Repeated s = s .. piece in a loop creates a new string each time, while collecting pieces in a table and calling table.concat once builds the result in one pass. Strings themselves are covered in Strings.

JS Stand-in: concat with a range and a type check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

table.sort

table.sort(t) sorts the list in place and returns nothing. By default it uses the < operator, so it works on all numbers or all strings, but mixing types raises an error (comparing a number with a string is an error in Lua).

Pass a comparator as the second argument to choose the order. The function receives two items a and b and must return true if a should come before b:

LUA
local scores = {42, 7, 19, 88}
table.sort(scores)                              -- 7, 19, 42, 88
table.sort(scores, function(a, b) return a > b end)  -- 88, 42, 19, 7

local people = {
  {name = "Zoe", age = 31},
  {name = "Adam", age = 25},
}
table.sort(people, function(a, b) return a.name < b.name end)

Two rules matter. First, the comparator must be a strict "less than": use <, never <=. A comparator that returns true for equal items can make Lua raise invalid order function for sorting, or in rarer cases produce garbage. Second, the sort is not stable. Items that compare as equal may end up in any relative order, and that order can differ between runs of different table contents. If you need a stable result, add a tie-breaker to the comparator, for instance the original position or a second field.

JS Stand-in: comparator and a tie-breaker

Press Run (or Ctrl + Enter) to see the console output here.

No output.

table.unpack and table.pack

table.unpack(t, i, j) returns the items t[i] to t[j] as separate values (defaults: 1 and #t). That lets you spread a list into function arguments or several variables:

LUA
local a, b, c = table.unpack({10, 20, 30})
print(math.max(table.unpack({4, 9, 2})))   --> 9

table.pack(...) does the opposite: it gathers its arguments into a new table and stores their count in the field n, which stays correct even when some arguments are nil. Varargs are explored in Varargs and Closures.

table.move

table.move(a1, f, e, t [, a2]) copies the items a1[f] to a1[e] to positions starting at t in a2 (the destination defaults to a1 itself) and returns the destination. It handles overlapping ranges safely, so it can shift items inside one table:

LUA
local list = {1, 2, 3, 4, 5}
table.move(list, 2, 5, 1)         -- {2, 3, 4, 5, 5}: shift left by one
local copy = table.move(list, 1, #list, 1, {})   -- a shallow copy
JS Stand-in: unpack, pack and move

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does table.remove(t) return when t is the empty table {}?

    On an empty sequence table.remove removes nothing and returns nil.
  2. 2. Which comparator is correct for sorting numbers from largest to smallest?

    The comparator must return true when a goes before b, and it must be a strict comparison. Using >= can raise 'invalid order function for sorting'.
  3. 3. Why might two people with the same age appear in different orders after table.sort?

    Lua's sort is not guaranteed to be stable. Add a tie-breaker field to the comparator when order of equal items matters.
  4. 4. What does table.concat({1, 2, 3}, ', ') produce?

    concat accepts strings and numbers. Numbers are converted, and the separator goes between items only.

Summary

  • table.insert(t, [pos,] v) and table.remove(t [, pos]) shift items to keep the sequence gap-free; remove returns the removed value.
  • table.concat(t, sep, i, j) joins strings and numbers and is the fast way to build big strings.
  • table.sort works in place; the comparator returns true when a goes before b, must be strict, and the sort is not stable.
  • table.unpack spreads a list into values; table.pack gathers values and records n.
  • table.move copies ranges and can also make a shallow copy.

Next, put these tools to work on sets, stacks, queues and matrices in Tables in Practice.