另一篇Lua面向对象

我之前写过一篇《Lua面向对象》,但那篇文章是我根据其它教程练习的,下面这篇是我自己写的,已经完全理解了Lua的面向对象机制,踩过几个坑。同时,这篇文章还附带了Lua的继承,这是在我理解了Lua的面向对象机制之后,完全自己写出来的,供新手参考。

Position = {x = 0, y = 0}

function Position:New()
    local o = {}
    setmetatable(o, {__index = self})
    o.x = 0
    o.y = 0
    return o
end

function Position:Move(x, y)
    self.x = self.x + x
    self.y = self.y + y
end

function Position:Report()
    print("position", self.x, self.y)
end

Position3 = Position:New()

function Position3:New()
    local o = {}
    setmetatable(o, {__index = self})
    o.z = 0
    return o
end

function Position3:Report()
    print("Position3", self.x, self.y, self.z)
end

function Position3:Move(x, y, z)
    self.x = self.x + x
    self.y = self.y + y
    self.z = self.z + z
end

local p1 = Position:New()
p1:Report()
p1:Move(3,5)
p1:Report()

local p2 = Position3:New()
p2:Report()
p2:Move(3,4,5)
p2:Report()