typestar

Nested tables in Lua

A dungeon is a table of room tables; access chains freely.

-- Tables nest freely: a dungeon is a table of room tables.
local dungeon = {
  { name = "cellar", danger = 1, loot = { "rope" } },
  { name = "crypt", danger = 4, loot = { "idol", "coins" } },
}

for _, room in ipairs(dungeon) do
  print(string.format("%s (danger %d): %d item(s)",
    room.name, room.danger, #room.loot))
end

-- Deep access chains dots and brackets.
print("Crypt's second find: " .. dungeon[2].loot[2])
dungeon[1].loot[#dungeon[1].loot + 1] = "chalk"
print("Cellar now holds: " ..
  table.concat(dungeon[1].loot, ", "))

How it works

  1. Literals nest: rooms hold loot arrays inside records.
  2. dungeon[2].loot[2] chains brackets and dots.
  3. t[#t + 1] = x is the idiomatic append.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
527
Tokens
132
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 122 seconds.

Type this snippet

Step 4 of 4 in Tables, step 10 of 27 in Language basics.

← Previous Next →