Tables are the primary composite data structure in the Lua programming language. They are used as containers, especially sequences (with consecutive numeric indexes starting from 1) and mappings (also known as associative arrays, dictionaries, or hashtables). Tables can be used as general purpose objects, and when combined with metatables (see Lua reference) can implement object-oriented concepts such as inheritance. Pico-8 includes several built-in functions for using tables.

Mappings Edit

Fundamentally, tables are mappings of keys to values. Key-value pairs are unordered. You can construct a new mapping using curly brackets. For example:

x = {a=1, b=2, c="hello"}

Values can be accessed using bracket notation, where the key is an expression (tbl["key"]).

print(x["a"])              -- 1

x["a"] = 99
print(x["a"])              -- 99

If the key is a string using the characters of a Lua identifier (letters, numbers, underscore, and begins with a letter), then the value can also be accessed using property notation (tbl.key).

print(x.b)                 -- 2

x.b = 88
print(x.b)                 -- 88

Accessing an unset key returns nil.

if x.d == nil then
  print("x.d is nil")

Pico-8 provides the built-in pairs(), which iterates over all key-value pairs in a table.

for k,v in pairs(x) do
  print(k.." = "..v)

Sequences Edit

A sequence is a table whose keys are a sequence of numbers starting with 1. Lua offers special syntax and features so that sequences behave somewhat like lists or arrays in other languages.

-- constructor syntax for sequences
y = {2, 3, 5, 7, 11}

print(y[1])           -- 2
print(y[5])           -- 11
if y[0] == nil then
  print("y[0] is nil")

-- the sequence length operator
print(#y)             -- 5

for i=1,#y do
  print("y["..i.."] = "..y[i])

A table that is a sequence is allowed to have other keys. The sequence part consists of all numbered keys starting from 1 ascending up to the first unset (nil) key.

y = {2, 3, 5, 7, 11, 13, 17}
print(#y)             -- 7

-- disconnect the latter part of the sequence with nil
y[4] = nil
print(#y)             -- 3

-- the other elements are still there, they're just not counted
print(y[5])           -- 11

Built-ins for sequences Edit

Pico-8 provides several built-ins that operate on sequences:

  • all(), which iterates over elements in the sequence in a table.
tbl = {2, 3, 5, 7, 11}
for v in all(tbl) do
  • add() appends a value to the end of a sequence.
  • del() removes the first element of the sequence that equals a given value, shifting all remaining elements down by one index to keep the sequence intact.
  • foreach() calls a given function for each element in the sequence, passing the element as the sole argument to the function.