local Vector = {}
local Vector_mt = { __index = Vector } -- Metatable for methods
function Vector.new(x, y, z)
local new_vec = { x = x or 0, y = y or 0, z = z or 0 }
setmetatable(new_vec, Vector_mt)
return new_vec
end
-- Overloading addition operator
function Vector_mt.__add(v1, v2)
return Vector.new(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)
end
-- Example method
function Vector:length()
return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end
local v1 = Vector.new(2, 1, 2)
--local v2 = Vector.new(4, 5, 6)
--local v3 = v1 + v2 -- Uses the __add metatable operation
print(v1.x, v1.y, v1.z) -- Output: 2, 1, 2 squareroot(2^2 + 1^2 + 2^2)
print(v1:length()) -- Output: 3
To embed this project on your website, copy the following code and paste it into your website's HTML: