Metatables & Operator Overloading

Metatables & Operator Overloading in Lua: Metatables are the mechanism that allows Lua tables to change their default behavior.

Metatables are the mechanism that allows Lua tables to change their default behavior. If tables are data objects, metatables are their underlying operational blueprints (similar to dunder methods in Python).


How Metatables Work

Every table in Lua can have an attached Metatable. When an operation (such as addition +, string concatenation .., or table lookup) is performed on a table, Lua checks whether its metatable defines a corresponding Metamethod (a key prefixed with double underscores __).

local setmetatable = setmetatable
local getmetatable = getmetatable

local t = {}
local mt = {}
setmetatable(t, mt) -- Attach mt as the metatable for t

Complete Metamethod Reference

MetamethodTriggering Event / Syntax
__add(a, b)Addition operator (a + b)
__sub(a, b)Subtraction operator (a - b)
__mul(a, b)Multiplication operator (a * b)
__div(a, b)Division operator (a / b)
__mod(a, b)Modulo operator (a % b)
__unm(a)Unary negation (-a)
__concat(a, b)String concatenation (a .. b)
__eq(a, b)Equality comparison (a == b)
__lt(a, b)Less than comparison (a < b)
__le(a, b)Less than or equal (a <= b)
__tostring(a)Called by print() and tostring()
__call(t, ...)When table is called as a function: t(...)

Real-World Example: Mathematical 2D Vector Library

local Vector2 = {}
Vector2.__index = Vector2

function Vector2.new(x, y)
    local self = setmetatable({}, Vector2)
    self.x = x or 0
    self.y = y or 0
    return self
end

-- Overloading the '+' operator
function Vector2.__add(a, b)
    return Vector2.new(a.x + b.x, a.y + b.y)
end

-- Overloading the '*' operator (Scalar multiplication or dot product)
function Vector2.__mul(a, b)
    if type(b) == "number" then
        return Vector2.new(a.x * b, a.y * b)
    elseif type(a) == "number" then
        return Vector2.new(b.x * a, b.y * a)
    end
    -- Dot product if both are vectors
    return (a.x * b.x) + (a.y * b.y)
end

-- Overloading string output
function Vector2.__tostring(v)
    return string.format("Vector2(%.2f, %.2f)", v.x, v.y)
end

-- Usage
local v1 = Vector2.new(3, 4)
local v2 = Vector2.new(1, 2)
local v3 = v1 + v2
local scaled = v1 * 2

print("v3 = " .. tostring(v3))       -- Vector2(4.00, 6.00)
print("scaled = " .. tostring(scaled)) -- Vector2(6.00, 8.00)

Protecting Metatables with __metatable

To prevent external scripts from inspecting or mutating your metatable, assign the __metatable field:

local secretMt = {
    __metatable = "Restricted Access: Cannot view or modify metatable!"
}
local secureObj = setmetatable({}, secretMt)

print(getmetatable(secureObj)) -- Output: Restricted Access: Cannot view or modify metatable!
-- setmetatable(secureObj, {}) -- Throws runtime error: cannot change a protected metatable

Exercises

  1. Build a ComplexNumber metatable supporting addition, multiplication, and clean formatting for imaginary numbers ($a + bi$).
  2. Overload the __call metamethod so that invoking a table myTable(x) adds x to an internal accumulator.
  3. Implement a custom set difference operator using __sub.