Lua継承の一例

3918 ワード

これを読めば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

まずコードを貼って、これから説明します.