二元运算符

运算符重载

local Point = {}
Point.__index = Point

function Point.new(x, y)
  return setmetatable({x = x, y = y}, Point)
end

function Point.__add(a, b)
  return Point.new(a.x + b.x, a.y + b.y)
end

function Point.__sub(a, b)
  return Point.new(a.x - b.x, a.y - b.y)
end

-- The result can be of any type: a dot product
function Point.__mul(a, b)
  return a.x * b.x + a.y * b.y
end

local p1 = Point.new(1, 1)
local p2 = Point.new(2, 2)
local p3 = p1 + p2
-- p3 = 3, 3
print("p3 = " .. p3.x .. ", " .. p3.y)

-- No += in Lua: the sum is written in full
p3 = p3 + Point.new(3, 5)
-- p3 = 6, 8
print("p3 = " .. p3.x .. ", " .. p3.y)

local diff = p3 - p1
-- diff = 5, 7
local dot = p3 * p2
-- dot = 28

print("diff = " .. diff.x .. ", " .. diff.y)
print("dot = " .. dot)