Codectionary / Developer documentation / Lua

Lua Tables

A Lua table maps keys to values. A sequence uses consecutive integer keys starting at 1; a record uses named fields. Both are tables, but sequence length and iteration rules are not dictionary-counting rules. Assigning a table to another variable shares the table rather than copying it.

Syntax

local topics = {"Tables", "Loops"}
local profile = {name = "Ada"}
print(topics[1])
print(profile.name)

Examples

Remove an item while keeping a sequence intact

table.remove shifts the later entries down. That keeps ipairs able to visit every remaining item in order.

local topics = {"Tables", "Loops", "Functions"}
local removed = table.remove(topics, 2)
print("Removed: " .. removed)
for index, title in ipairs(topics) do
    print(index .. ": " .. title)
end
print("Length: " .. #topics)
  1. Output is Removed: Loops, then 1: Tables, 2: Functions, and Length: 2. table.remove also returns the removed value.
  2. Setting topics[2] = nil would remove the key without moving Functions down. ipairs stops at the first absent integer key, so that hole would stop the traversal early.
  3. For this dense sequence, # gives its length. Do not use # as a count of dictionary entries or rely on its result for a table with holes.

See why changing an alias changes the original

Named fields are useful for a record. A second variable can point to the same record, so a change through either name is visible through both.

local profile = {name = "Ada", completed = 2}
local alias = profile
alias.completed = alias.completed + 1
print(profile.name .. ": " .. profile.completed)
print(profile == alias)
local fieldCount = 0
for _ in pairs(profile) do
    fieldCount = fieldCount + 1
end
print("Fields: " .. fieldCount)
  1. Output is Ada: 3, then true, then Fields: 2. The assignment did not create a second table; both variables refer to the same one.
  2. profile.name is shorthand for profile["name"]. pairs visits the present fields, without promising their order; the loop counts them regardless of that order.
  3. Add profile.active = false and the field count becomes 3. Assign nil instead and the key is absent: false is a stored value, while nil removes a field.

Best practices

  • Keep sequences dense when using ipairs, # or table.remove.
  • Count dictionary entries with pairs rather than #, and never depend on pairs ordering.
  • Copy fields into a new table if you need independent top-level state; nested tables would still need their own copying policy.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading