I had to make an assumption in here, but here's what you asked for as far as I could figure out
Code: Select all
--Vector implemented globally. With the implementation suggested, this must be a global or else the metamethods don't know what a
--vector is. Take a look into scope if you want to know more on this.
vector = {
mt = {
__add = function(a, b)
return vector.new(a.x + b.x, a.y + b.y)
end,
__sub = function(a, b)
return vector.new(a.x - b.x, a.y - b.y)
end
},
new = function(x, y)
return setmetatable({x=x, y=y}, vector.mt)
end
}
local p1 = vector.new(1, 1)
local p2 = vector.new(2, 2)
local p3 = p1 + p2
print(p3.x, p3.y)
Instead of an implementation such as
Code: Select all
local self = { <--Not a good variable name.
["x"] = x and x or 0,
["y"] = y and y or 0
}
I'm unable to figure out what type of object this is. Is this how you're choosing to instance your vector?
If this is some type of game entity, its metatable wouldn't really be a vector. Make sure to name your variables more descriptively.
Code: Select all
local entity = {
position = vector.new(0, 0),
}
entity.position.x = 10
entity.position.y = 20
Remember: In a method call, lua defines "self" as the table invoking the call. Read more on metatables for a better understanding of that.
Code: Select all
local tbl_a = {}
function tbl_a:method()
self.a = 1
end
--In this case, self refers to tbl_a
tbl_a:method()
--In this case, self also refers to tbl_a
tbl_a.method(tbl_a)
local tbl_b = {}
--In this case, self refers to tbl_b.
tbl_a.method(tbl_b)