typestar

__index in Lua

Missed lookups go to the fallback: inheritance in one line.

-- __index sends missed lookups elsewhere: inheritance in one line.
local defaults = { hp = 20, speed = 4, torch = true }

local goblin = setmetatable({ hp = 7 }, { __index = defaults })

print("Goblin hp (own): " .. goblin.hp)
print("Goblin speed (inherited): " .. goblin.speed)

-- Writing touches only the table itself, never the fallback.
goblin.speed = 6
print("Goblin speed (now own): " .. goblin.speed)
print("Defaults untouched: " .. defaults.speed)

How it works

  1. setmetatable(t, { __index = defaults }) wires the chain.
  2. Reads fall through; goblin.speed comes from defaults.
  3. Writes stay on the table itself — the fallback never changes.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
457
Tokens
77
Three-star pace
65 tpm

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

Type this snippet

Step 1 of 3 in Metatables, step 17 of 27 in Language basics.

← Previous Next →