Lua物件導向利用metamethod重載運算子

來源:互聯網
上載者:User

標籤:io   os   java   for   sp   div   c   on   cti   

利用Point作為例子
local math = require("math")local Point = {x = 0, y = 0}Point.__index = Pointfunction 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 selfend-- 兩點相加function Point.__add(p1, p2)    local p3 = Point.new({x = p1.x + p2.x, y = p1.y + p2.y})    return p3end-- 兩點相減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.yend-- 兩點距離function Point:distance(p2)    return math.sqrt(math.pow(self.x - p2.x, 2) + math.pow(self.y - p2.y, 2))endfunction Point.__tostring(p1)    return "x="..p1.x.." y="..p1.yendlocal p1 = Point.new()print(p1)local p2 = Point.new(1, 2)print(p2)local p3 = Point.new(p2)print(p3)local p4 = p2 + p3print(p4)local p5 = p4 - p2print(p5)local p6 = p4 * p5print(p6)local p7 = p6 / p4print(p7)print(p7 == p6)print(p7:distance(p6))print(p7)

輸出

x=0 y=0x=1 y=2x=1 y=2x=2 y=4x=1 y=2x=2 y=8x=1 y=2false6.0827625302982x=1 y=2

Lua物件導向利用metamethod重載運算子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.