Metatables
Metatables are the Lua method for creating objects and altering the behavior of operators such as +, -, [], etc.
Every value in Lua can have a metatable. This metatable is an ordinary Lua table
that defines the behavior of the original value under certain special operations. You can change
several aspects of the behavior of operations over a value by setting specific fields in its
metatable. For instance, when a non-numeric value is the operand of an addition, Lua checks for a
function in the field "__add"
in its metatable. If it finds one, Lua calls this
function to perform the addition.
We call the keys in a metatable events and the values metamethods. In the previous
example, the event is "add"
and the metamethod is the function that performs the
addition.
Tables and full userdata have individual metatables (although multiple tables and userdata can share their metatables). Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc.
A metatable controls how an object behaves in arithmetic operations, order comparisons, concatenation, length operation, and indexing. For each of these operations Lua associates a specific key called an event. When Lua performs one of these operations over a value, it checks whether this value has a metatable with the corresponding event. If so, the value associated with that key (the metamethod) controls how Lua will perform the operation.
Metatables control the operations listed next. Each operation is identified by its corresponding
name. The key for each operation is a string with its name prefixed by two underscores,
'__
'; for instance, the key for operation "add" is the string
"__add"
. The semantics of these operations is better explained by a Lua function
describing how the interpreter executes the operation.