【步兵 lua】模拟继承

【步兵 lua】模拟继承 by EOS.

lua中的继承可能见过许多中了,比如cocos源码里的,是比较高级的。
但本文这种的写法,是适应我的习惯。 = 3=

class.lua

if new then return end

new = {}

class = function (clsName, super)
    if(new[clsName])then error("!!! class ["..clsName.."] is Exist") end

    local cls = nil

    if super then
        cls = {}
        setmetatable(cls, super)
        cls.super = super
    else
        cls = {}
    end
    cls.className = clsName
    cls.__index = cls

    new[clsName] = function(...)
        local instance = setmetatable({}, cls)
        instance:init(...)
        return instance
    end

    return cls
end

BaseLayer.lua

if BaseLayer then return end

require "class"

BaseLayer = class("BaseLayer")
BaseLayer.fuck = 3
function BaseLayer:init()
    self.x = 0
    self.y = 0
    self.width = 100
    self.height = 150
end
function BaseLayer:show()
    print "BaseLayer Show"
end
function BaseLayer:logProperty()    
    print("myClassName = "..self.className)
    print("x:"..self.x)
    print("y:"..self.y)
    print("width:"..self.width)
    print("height:"..self.height)
end

HelloLayer .lua

if HelloLayer then return end

require "class"
require "BaseLayer"

HelloLayer = class("HelloLayer", BaseLayer)

function HelloLayer:init(width, height)
    self.super:init()
    self.super.fuck = 2
    if width and height then
        self.width = width
        self.height = height
    end
end

main.lua

require "class"
require "HelloLayer"

function main()
    --继承测试
    local helloLayer = new.HelloLayer(200, 250)
    helloLayer:show()
    helloLayer:logProperty()
end

main()

输出

这里写图片描述

其他

至于if new then return end之流,在文件中加入print之类的函数,
require多次,会多次执行,加上之后只会执行一次,应该会起到优化作用~

一天三连发,你怕不怕=。= , 累屎了,碎觉!!

See Again~
之前
真爱无价,欢迎打赏~
赞赏码

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值