cocos2dx lua中使用class实现继承api中的类

来源:互联网 发布:淘宝怎么天天特价 编辑:程序博客网 时间:2024/04/29 09:57

如果需要扩展api中的类时,使用继承的方式,需要重写的就重写,需要扩展就扩展

直接上代码,代码中有解释


require "extern"    --使用class方法需要的extern.lua模块--调用父类方法function getSuperMethod(table, methodName)    local mt = getmetatable(table)    local method = nil    while mt and not method do        method = mt[methodName]        if not method then            local index = mt.__index            if index and type(index) == "function" then                method = index(mt, methodName)            elseif index and type(index) == "table" then                method = index[methodName]            end        end         mt = getmetatable(mt)    end    return methodend--自定义类继承sprite,前提是这个sprite必须先绑定好c++中的spriteMyCustom = class("MyCustom",function(filename)  --通过返回一个sprite实现继承sprite类,    return cc.Sprite:create(filename)           --这里的function就是下面的MyCustom.newend)MyCustom.__index = MyCustom     --索引访问MyCustom.aaa = 0    --定义属性及对应值function MyCustom:create(filename , aaa)        local mySpr = MyCustom.new(filename)    --这里使用的是''.",不是":"    self.aaa = aaa  --设置属性值    return mySprend-- 实现重写父类方法function MyCustom:setVisible(visible)    getSuperMethod(self, "setVisible")(self, visible) --调用父类方法并传递参数    print("override setVisible method")end


0 0
原创粉丝点击