Skip to content

Metatables

A metatable is in general just a regular table, but it containts control functions. Here is a list of control functions:

Name Description
__index Used to lookup keys in a table if none was found
__newindex Used to create new keys or update existing ones in a table
__call Called when a table is being called
__tostring Called when a table is being converted to a string (on concatenation for example)
__concat Called when a table is being concatenated with something
__metatable Used to return a metatable object. Can be set to nil to hide the metatable
__mode Used to control the GC (garbage collector)
__gc Called when the GC is collecting this exact table
__add + operator
__sub - operator
__mul * operator
__div / operator
__pow ^ operator
__mod % operator
__eq == operator
__lt < operator
__le <= operator

__index

Can be a table too lookup in or a function:

1
2
3
4
table.__index = {
    a = 'b',
    c = 'd'
}
1
2
3
4
function __index(self, key)
    -- ...
    return VALUE
end

__newindex

1
2
3
function __newindex(self, key, value)
    -- ...
end

The following code will restrict table keys from writing:

1
2
3
function __newindex(self, key, value)
    return
end

__call

1
2
3
4
function __call(self, ...)
    -- ...
    -- optional return
end

__tostring

1
2
3
4
function __tostring(self)
    -- ...
    return 'string'
end

__concat

1
2
3
4
function __concat(a, b)
    -- ...
    return tostring(a) .. tostring(b)
end

Operators overload

All operator overloads have the same structure:

1
2
3
4
function OPERATOR(left, right)
    -- do comparison/add/sub/etc
    return VALUE
end