Game Development Reference
In-Depth Information
Metatables
One of the most powerful concepts of Lua is its ability to modify the behavior of
tables. For example, it is typically illegal to attempt to add two tables together.
Using metatables, you could define behavior where this is valid.
A metatable is just another table. There
'
s nothing particularly special about it. Any
table may be the metatable for any other table. Metatables may have metatables them-
selves, and multiple tables can have the same metatable that defines a set of common
behaviors. A table can even be its own metatable! By default, tables have no metatable.
Metatables are use by Lua when it encounters certain situations. For example, when
Lua attempts to add two tables, it first checks to see if either table has a metatable. If
so, it checks to see if one of them defines a variable named __add . It then calls this
variable (which should be a function). The __add field is a metamethod, which is a
predefined field that Lua looks for in that situation. There are many such meta-
methods, several of which you
ll see below.
You can get and set the metatable of a table with getmetatable() and setmeta-
table() .
'
x = {} -- empty table
print(getmetatable(x)) -- > nil; tables don
'
t have metatables by default
y={}
setmetatable(x, y) -- y is now the metatable for x
-- This block will print
Success
if getmetatable(x) == y then
print(
Success
)
else
print(“Fail”)
end
In order to be useful, you need to set metamethod fields on the metatable. The meta-
method we
t find a field you
are attempting to read. For example, say you have the following code:
'
re interested in is __index , which is used when Lua can
'
x={}
print(x.y)
The output of the print statement will be nil .What
s really happening is that Lua
looks at the x table and checks to see if it has a field called y . If it does, it returns this.
If not, it checks to see if the table has a metatable. If it does, it checks to see if that
metatable has the __index metamethod and, if it does, calls it, returning the result as
the value for y .Ifthe __index field is another table, Lua attempts the same access on
'
 
 
Search WWH ::




Custom Search