示例工程 14-metatables-and-operators
14-metatables-and-operators/01-vector-arithmetic/main.lua
-- @runtimes lua54 luajit
--- 演示:__add/__mul 实现向量运算。
local M = {}
local Vector = {}
Vector.__index = Vector
local function new(x, y)
return setmetatable({ x = x, y = y }, Vector)
end
Vector.__add = function(a, b)
return new(a.x + b.x, a.y + b.y)
end
Vector.__mul = function(a, scalar)
return new(a.x * scalar, a.y * scalar)
end
Vector.__tostring = function(v)
return ("(%d,%d)"):format(v.x, v.y)
end
--- @return table { sum = string, scaled = string }
function M.run(log)
log = log or print
local sum = new(1, 2) + new(3, 4)
local scaled = new(2, 3) * 2
log(("sum=%s scaled=%s"):format(tostring(sum), tostring(scaled)))
return { sum = tostring(sum), scaled = tostring(scaled) }
end
if not ... then
M.run()
end
return M