BudiBadu Logo
Samplebadu

Lua by Example: Metatables

Lua 5.4

Metatables allow you to change the behavior of tables. This example shows how to implement operator overloading and custom indexing.

Code

local meta = {
    -- Overload the + operator
    __add = function(t1, t2)
        return { value = t1.value + t2.value }
    end,
    
    -- Custom string representation
    __tostring = function(t)
        return "Value: " .. t.value
    end
}

local function createBox(val)
    local box = { value = val }
    setmetatable(box, meta)
    return box
end

local b1 = createBox(10)
local b2 = createBox(20)
local b3 = b1 + b2 -- Uses __add

print(b3) -- Uses __tostring: Value: 30

Explanation

Metatables are the mechanism Lua uses to overload operators and define custom behavior for tables. By attaching a metatable to a table, you can define how that table behaves when you try to add it to another table, print it, or access a key that doesn't exist.

Special keys in the metatable, prefixed with double underscores (like __add, __tostring, __index), are called metamethods. When an event occurs (like addition), Lua checks if the table has a metatable with the corresponding metamethod and executes it.

This system is powerful enough to implement object-oriented programming classes, prototypes, and inheritance. The __index metamethod is particularly useful; it acts as a fallback when a key is missing in the table, allowing you to delegate lookups to another table (a parent class).

Code Breakdown

3
__add is the metamethod key for the addition operator +.
15
setmetatable(box, meta) associates the behavior defined in meta with the specific table box.