Skip to content

Lesson 2 of 9 · 24m

Tables and Metatables: Lua's Object System in Plain Sight

How __index, __newindex, operators, and prototype chains turn one table type into objects, defaults, validation, and controlled extension points.

Metatables are where Lua stops looking small and starts looking clever. They are also where production scripting systems quietly become impossible to debug. A metatable is just a table attached to another table that supplies fallback behavior when normal table rules fail. Used with restraint, it gives you objects and defaults. Used creatively everywhere, it turns a missing key into a program execution.

Prototypes are delegation, not magic

local Enemy = {}
Enemy.__index = Enemy

function Enemy.new(name, health)
  return setmetatable({ name = name, health = health }, Enemy)
end

function Enemy:take_damage(amount)
  self.health = math.max(0, self.health - amount)
end

local imp = Enemy.new("imp", 12)
imp:take_damage(5)
print(imp.health)  -- 7

The colon syntax is sugar: imp:take_damage(5) means imp.take_damage(imp, 5). The crucial line is Enemy.__index = Enemy. When take_damage is missing on the instance, Lua looks it up on the prototype.

__index can also be a function: __index = function(_, key) return "missing:" .. key end. That is useful for defaults and terrible for typos. If every miss returns something plausible, misspellings stop failing; production configuration should usually fail fast.

Controlled writes with __newindex

__newindex runs when assignment would create a new key. It can validate, redirect, or reject writes:

local backing = {}
local settings = setmetatable({}, {
  __index = backing,
  __newindex = function(_, key, value)
    if key == "max_health" and type(value) ~= "number" then
      error("max_health must be a number", 2)
    end
    backing[key] = value
  end,
})

Use rawget and rawset when you intentionally need to bypass metamethods inside your own implementation. If those functions appear all over business logic, the abstraction is leaking.

Operator metamethods have narrow uses

__add, __eq, __lt, __le, __concat, and __tostring can make vectors and money types pleasant. But metamethods are invisible control flow. A maintainer reading a + b cannot tell whether a network call, allocation, or invariant check is hiding there.

Field notes

  • setmetatable returns the original table; it does not copy it.
  • Metatables are per-table, not per-type. Two seemingly identical objects can behave differently.
  • pairs order is unspecified. Never rely on printed table order in tests.
  • Protect host-owned objects from script mutation: expose read-only proxy tables and validate writes in __newindex rather than trusting sandbox users.
  • Deep prototype chains are a debugging tax. One or two levels is normal; six is a framework pretending to be a language.

Was this lesson helpful?

Sign in to rate