Game Development Reference
In-Depth Information
t=setmetatable({},{__tostring=function() return "This is my custom table" end})
print(t)
print(tostring(t))
__gc
This function is called when the table is set to be garbage collected. If __gc is pointing to a function,
this function is first invoked. This function is only available for user data (i.e., usable via the C APIs).
__unm
- sign. To convert a number into a negative
Note In this example, we are returning a fixed number, -3. In your program, you might want to calculate the
value to return.
__add
This function is the normal addition function; it is called when adding a variable to a table object
using the + operator. Overriding this can be very useful when trying to add objects that do not have a
numeric value that can be simply added.
The first example that comes to mind is that of fractions. This is perhaps one of the most common
examples of operator overloading with C++ and using addition between two objects that are
nonnumeric.
t = setmetatable({},{__add=function(tbl, val) return 5+val end})
print(t+5)
Caution Do not call this as print(5 + t) , which can lead to stack overflows. The table has to be
the leftmost value for this to work, as the function __add expects the first parameter to be a table value.
 
 
Search WWH ::




Custom Search