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
- Literals nest: rooms hold loot arrays inside records.
dungeon[2].loot[2]chains brackets and dots.t[#t + 1] = xis the idiomatic append.
Keywords and builtins used here
doendforinipairslocalprint
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.
Step 4 of 4 in Tables, step 10 of 27 in Language basics.