typestar

Tables as records in Lua

String keys and dot access make the same table a record.

-- The same table plays record: string keys, dot access.
local hero = {
  name = "Wren",
  class = "cartographer",
  hp = 20,
}

print(hero.name .. " the " .. hero.class)

-- Dot and bracket notation reach the same slot.
hero.hp = hero.hp - 6
hero["last_room"] = "cellar"
print(string.format("%d hp after the %s", hero.hp, hero.last_room))

-- Missing keys read as nil, never an error.
print("Familiar: " .. tostring(hero.familiar))

How it works

  1. hero.name and hero["last_room"] reach the same kind of slot.
  2. Assignment adds fields at any time.
  3. Missing keys read as nil — never an error at read time.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
426
Tokens
85
Three-star pace
70 tpm

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

Type this snippet

Step 2 of 4 in Tables, step 8 of 27 in Language basics.

← Previous Next →