Skip to content
Metatables
step 1/5

Reading — step 1 of 5

Learn

~1 min readMetatables and OOP

A metatable is a hidden table attached to another table. When operators or operations don't find what they need on a value, Lua looks at the metatable.

local vec1 = {x = 1, y = 2}
local vec2 = {x = 3, y = 4}

-- print(vec1 + vec2)  -- ERROR: attempt to perform arithmetic on a table

local mt = {
    __add = function(a, b)
        return {x = a.x + b.x, y = a.y + b.y}
    end,
    __tostring = function(v)
        return string.format("(%d, %d)", v.x, v.y)
    end,
}

setmetatable(vec1, mt)
setmetatable(vec2, mt)

local sum = vec1 + vec2       -- triggers __add
print(tostring(sum))           -- triggers __tostring: "(4, 6)"

Common metamethods:

  • __add, __sub, __mul, __div, __mod, __pow, __unm — arithmetic
  • __eq, __lt, __le — comparison
  • __concat.. operator
  • __len# operator
  • __index — fallback for missing keys (next lesson)
  • __newindex — intercepts assignment to missing keys
  • __call — make a table callable like a function
  • __tostring — custom string conversion

Metatables are how Lua provides operator overloading, OO, proxies, and lazy evaluation — all without adding language constructs.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…