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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值