Lua面向对象利用metamethod重载运算符

利用Point作为例子

local math = require("math")
local Point = {x = 0, y = 0}
Point.__index = Point
function Point.new(x, y)
    local self = setmetatable({}, Point)
    if (type(x) == "table") then
        for k, v in pairs(x) do
            self[k] = v
        end
    elseif (type(x) == "number" and type(y) == "number") then
        self['x'] = x
        self['y'] = y
    end
    return self
end

-- 两点相加
function Point.__add(p1, p2)
    local p3 = Point.new({x = p1.x + p2.x, y = p1.y + p2.y})
    return p3
end

-- 两点相减
function Point.__sub(p1, p2)
    return Point.new({x = p1.x - p2.x, y = p1.y - p2.y})
end

-- 两点相乘
function Point.__mul(p1, p2)
    return Point.new({x = p1.x * p2.x, y = p1.y * p2.y})
end

-- 两点相除
function Point.__div(p1, p2)
    return Point.new({x = p1.x / p2.x, y = p1.y / p2.y})
end

-- 相等
function Point.__eq(p1, p2)
    return p1.x == p2.x and p1.y == p2.y
end

-- 两点距离
function Point:distance(p2)
    return math.sqrt(math.pow(self.x - p2.x, 2) + math.pow(self.y - p2.y, 2))
end

function Point.__tostring(p1)
    return "x="..p1.x.." y="..p1.y
end


local p1 = Point.new()
print(p1)

local p2 = Point.new(1, 2)
print(p2)

local p3 = Point.new(p2)
print(p3)

local p4 = p2 + p3
print(p4)

local p5 = p4 - p2
print(p5)

local p6 = p4 * p5
print(p6)

local p7 = p6 / p4
print(p7)

print(p7 == p6)

print(p7:distance(p6))
print(p7)

输出

x=0 y=0
x=1 y=2
x=1 y=2
x=2 y=4
x=1 y=2
x=2 y=8
x=1 y=2
false
6.0827625302982
x=1 y=2

你可能感兴趣的:(lua,metamethod)