local Point = {}
Point.__index = Point
function Point.new(x, y)
return setmetatable({x = x, y = y}, Point)
end
-- The set of operators is fixed: an existing
-- one gets a new meaning for the class.
-- ^ raises each coordinate to the power
function Point.__pow(p, power)
return Point.new(p.x ^ power, p.y ^ power)
end
-- ~ (bitwise xor) becomes the distance by axes
function Point.__bxor(a, b)
return math.abs(a.x - b.x) + math.abs(a.y - b.y)
end
local p1 = Point.new(2, 3)
local p2 = p1 ^ 3
-- p2 = 8.0, 27.0
local distance = p1 ~ Point.new(5, 1)
-- distance = 5
-- A new operator is a syntax error:
-- load returns nil and the message
local chunk, err = load("return p1 <=> p2")
-- chunk = nil
-- err = [string "return p1 <=> p2"]:1:
-- unexpected symbol near '>'
print("p2 = " .. p2.x .. ", " .. p2.y)
print("distance = " .. distance)
print("chunk = " .. tostring(chunk))
print("err = " .. err)