Game Development Reference
In-Depth Information
__concat
This is the concatenation function, which is called when the concatenation operator (
..
) is used to
concatenate two or more table values.
t = setmetatable({}, {__concat=function(tbl,val) return "Hello " .. val end})
print(t .. "Jayant")
__eq
This is the equal operator (
==
); it can be used to help compare two table values that are not easily
comparable. The
not (a==b)
is equivalent to
a~=b
.
less-than
operator (
<
); it can be used to help compare two table values that are not easily
less-than-or-equal-to
operator (
<=
) is also useful for comparing two table values that are not
A Useful Example
Let's look at a sample that demonstrates the practical use of the functions just described and their
use with tables. The
+
operator works well between numbers. If we try to add two tables using the
+
operator, it will not work. We can create the functions that can be used to manage operations such
as adding these tables. In the following example, we override the
__add
function, which allows us to
add two tables using the
+
operator.
thePos = {}
thePos.__add = function (a, b)
local res = {
a[1] + b[1],
a[2] + b[2]
}
setmetatable(res, thePos)
return res
end
function make_pos(x,y)
local res = { x, y }
setmetatable(res, thePos)
return res
end