Code
lua
-- Vector class via metatable
local Vector = {}
Vector.__index = Vector -- lookups fall through to Vector
function Vector.new(x, y)
local self = setmetatable({}, Vector)
self.x = x or 0
self.y = y or 0
return self
end
-- Operator overloading
function Vector.__add(a, b)
return Vector.new(a.x + b.x, a.y + b.y)
end
function Vector.__tostring(self)
return string.format("(%d, %d)", self.x, self.y)
end
-- Method
function Vector:length()
return math.sqrt(self.x^2 + self.y^2)
end
-- Usage
local v1 = Vector.new(3, 4)
local v2 = Vector.new(1, 2)
local v3 = v1 + v2 -- (4, 6)
print(v3) -- (4, 6) (uses __tostring)
print(v3:length()) -- 7.21
print(getmetatable(v1)) -- Vector table