Lua继承的一个例子

如果看懂了这个就能明白通过metatable在继承的意义,也能理解:和.的差异。

main.lua

require("base")
require("actor")


function main()
    local obj = actor.new("tiny")
    obj:init()
    obj:say_hi()
    obj:work()
end

main()

base.lua

_G.base = {
    init = function(self)
        self.x = 10
        self.y = 10
        print("base.lua init")
    end,

    say_hi = function(self)
        print( string.format("base.lua say_hi x: %d, y: %d",self.x,self.y))
    end,

    work = function(self)
        print("this is base work")
    end
}

actor.lua

_G.actor = {}
setmetatable(_G.actor,{__index = _G.base })

function new(name)
    obj = {name = name}
    setmetatable(obj,{__index = _G.actor })
    return obj
end

function init(self)
    getmetatable(getmetatable(self).__index).__index.init(self)
    self.hp = 10
end

function say_hi(self)
    getmetatable(getmetatable(self).__index).__index.say_hi(self)
    print(string.format("actor this is actor:say_hi, hp: %d", self.hp))
end

_G.actor.new = new
_G.actor.init = init
_G.actor.say_hi = say_hi

输出信息

base.lua init
base.lua say_hi x: 10, y: 10
actor this is actor:say_hi, hp: 10
this is base work

先将代码贴出来,今后来做解释。

你可能感兴趣的:(Lua)