Game Development Reference
In-Depth Information
Customizing the Metatable
Remember that in Lua, one of the most important types of variables is the table. As mentioned, arrays,
associative arrays, and objects are all basically tables. Arrays aren't very customizable, but objects
are—they have some extra functionality and functions that arrays don't. All of this functionality forms
a unique fingerprint for the object, and that helps identify the object type. Every table in Lua can
have a metatable. A metatable is nothing more than an ordinary table that defines the behavior of the
original table and the user data. If we set specific fields in the metatable, we can modify the behavior
of the object. We can thereby create objects and allow them to have custom operations, similar to
C++ operator overloading. However, there is a limited list of what can be altered in Lua.
The following subsections describe the keys that help Lua to alter or customize the behavior of
tables.
__index
When we attempt to retrieve the value of an element in a Lua table, Lua attempts to locate that
element; if the element does not exist, then Lua calls the __index metafunction. If there is no such
method, then nil is returned.
For example, say we run the following code:
t = {}
print(t.name)
print(t.age)
This prints nil for both the name and the age, because we have not defined them yet. If we modify
this code to include
default = { name ="Lua" }
t = setmetatable( {}, {__index=default} )
print(t.name)
print(t.age)
we see that the first print displays “Lua” and the second still prints nil .
The __index metafunction can be the data in a table, as in the preceding code, or it can be a function.
When the __index function is called, it is passed two parameters: the Table and the Key .
We can see this behavior with the following code:
t = setmetatable({}, {__index=function(theTable, theKey) print(theTable, theKey)
return"." end})
print(t.name)
print(t.age)
print(t[1])
print(t[2][3])
print(t.whatever)
We are returning a . from the function, so we see it print the table address and the name of the
element that we are trying to access, followed by a . .
 
Search WWH ::




Custom Search