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…