Game Development Reference
In-Depth Information
__sub
This function is the normal subtraction function, which is called when subtracting a variable from a
table object using the - operator. Overriding this can be very useful when trying to subtract objects
that do not have a numeric value that can be simply subtracted.
t = setmetatable({},{__sub=function(tbl, val) return 5-val end})
print(t-3)
Note Again, do not call this as print(3 - t) , which can lead to stack overflows. The table has to be
the leftmost value for this to work, as the function __sub expects the first parameter to be a table value.
__mul
This function is the normal multiplication function, called when multiplying a variable from a table
object using the * operator. Overriding this can be useful when trying to multiply objects that do
not have a numeric value that can be simply multiplied. A good example is when trying to get a dot
product of a matrix or a vector.
t = setmetatable({},{__mul=function(tbl, val) return 2^val end})
print(t * 3)
print(2 * 2)
In this example, depending on the value we multiply by, we are returning 2 to the power of that
number; this is an example of how we can have functionality that is closest to operator overloading
in Lua.
__div
This is the normal division function, called when dividing a variable from a table object using the
/ operator. Overriding this can be very useful when trying to divide objects that do not have a
numeric value that can be simply divided.
t = setmetatable({},{__div=function(tbl, val) return 1/val end})
print(t/3)
__pow
This is the normal exponential function, called when using the ^ operator. Overriding this can be
useful when trying to execute operations that do not have a numeric value that can be used simply.
t = setmetatable({},{__pow=function(tbl, val) return 7^val end})
print(t^3)
 
Search WWH ::




Custom Search