Hi. This morning I figured that using position in using standard arrays is horrible :O.
So.. This simple code makes it a bit simpler to compare, add and subtrac positions using normal math operators.
I tested it, there is some kind os issues when we speak about z coordinate. But I hope you can notice what I mean yourself. Its not a big deal. Maybe someone would like to rewrite it, or add some new functionalities. Feel free to do it. : )
So.. This simple code makes it a bit simpler to compare, add and subtrac positions using normal math operators.
I tested it, there is some kind os issues when we speak about z coordinate. But I hope you can notice what I mean yourself. Its not a big deal. Maybe someone would like to rewrite it, or add some new functionalities. Feel free to do it. : )
Code:
Position = {}
function Position.isValid(arr)
return type(arr.x) == "number" and type(arr.y) == "number" and type(arr.z) == "number"
end
function Position.print(arr)
print("Position representation", unpack(arr))
end
function Position:new(x,y,z)
local obj = {}
if type(x) == "table" and Position.isValid(x) then
obj.pos = x --we passed position as one argument
else
obj.pos = {x = x, y = y, z = z}
end
self.__index = self
self.__add = function(a,b)
if Position.isValid(a()) and Position.isValid(b()) then
local result = {x = a().x +b().x, y = a().y + b().y, z = a().z }
return self:new(result)
end
return error("You are attemping to add something else than positions objects")
end
self.__sub = function(a,b)
if Position.isValid(a()) and Position.isValid(b()) then
local result = {x = a().x -b().x, y = a().y - b().y, z = a().z }
return self:new(result)
end
return error("You are attemping to subtrack something else than positions objects")
end
self.__eq = function(a, b)
self.print(a)
self.print(b)
if Position.isValid(a()) and Position.isValid(b()) then
local result = (a().x ==b().x and a().y == b().y and b().z == a().z )
return result
end
return error("You are attemping to compare something else than positions objects")
end
self.__call = function(s)
--if we call object like function it will return its position array.
return s.pos
end
return setmetatable(obj,self)
end
local pos1 = Position:new(3,4,5)
local pos2 = Position:new(4,5,6)
local pos3 = Position:new(3,4,5)
local pos4 = Position:new({x=3, y=4,z = 5})
local pos5 = pos1+pos2
local pos6 = pos3 + pos2
print(tostring(pos1 == pos2))
print(tostring(pos1 == pos3))
print(tostring(pos1 == pos4))
print(pos5().x, pos5().y, pos5().z)
print(pos6().x, pos6().y, pos6().z)
print(tostring(pos5 == pos6))