table

Contents

table#

The one composite type. A table is an associative array; keys can be any value except nil or NaN; values can be any type. Tables play three roles in Lua: sequence (integer keys 1..n), hash map (arbitrary keys), and record / module (string keys, used like fields).

Sequence form (integer keys from 1).

local arr = {10, 20, 30}
print(arr[1], arr[2], #arr)          --> 10  20  3

Record form (string keys).

local map = {name = "rk", age = 30}
print(map.name)                      --> rk

Bracket access with a string key.

print(map["name"])                   --> rk

Mixed sequence + hash in one literal.

local mixed = {1, 2, key = "v"}

Sequence rules. #t returns a boundary, defined only when the sequence is “honest” (no nil holes from 1 to n). Inserting nil into the middle of a sequence breaks # and ipairs. Use ipairs for sequences and pairs for everything else.

Walk a sequence in order.

local xs = {10, 20, 30}
for i, v in ipairs(xs) do print(i, v) end

Walk every key-value pair (any order).

for k, v in pairs(map) do print(k, v) end

See Data Structures for the full vocabulary of patterns tables support (array, set, queue, namespace).

References#