Game Development Reference
In-Depth Information
Note This function is called the very first time, when the value of the key is not set at all. If the value is
set, the function is not invoked at all. The value is directly altered.
__mode
In programming languages like Lua that employ garbage collection, objects are said to be weak if
they cannot prevent themselves from being collected. Lua can set the table as a weak table where
the keys and the values are weak references. If the key or the value of such a table is collected, the
entry of the table is collected.
The mode of these weak tables can be set using the __mode metafunction, and it can be used to set
the keys or the values as weak using the k or v parameter, as follows:
local weaktable = setmetatable({}, {__mode="k"})
__call
This allows the table to be used like a function. If the table is followed by parentheses, the metatable
tries to locate the __call function and invoke it; if it is not present, it returns an error. Otherwise, it is
passed the table and the arguments passed.
t = setmetatable({},{
__call = function(t, value)
print("Calling the table with " .. value)
end})
t("2012")
Note Every time the metatable is set, it overwrites the earlier metatable entries, which means that in the
preceding example, we do not have an entry for __newindex . If we had that defined earlier, it would have
been removed, and the only function set would have been __call . You need to define all the relevant keys
in one go, or get the metatable and then add or alter the new metafunction.
__metatable
This hides the metatable. When the getmetatable function is used and the table has a __metatable
string, then the value of that key is returned instead of the actual metatable.
__tostring
This function is called when a sting representation of a table or object is requested. This can be used
to provide a description for custom objects.
 
Search WWH ::




Custom Search