lua中的继承

在lua中写一个继承自CCLayer的类
local scheduler = require(“framework.scheduler”)
local RuleLayer = class(“RuleLayer”, function ()
return display.newLayer()
end)
function RuleLayer:ctor()
– cc.LuaLog(“RuleLayer:ctor”)
self:setNodeEventEnabled(true)
end

return RuleLayer

在写一个BatmanSubLayer继承自RuleLayer
local RuleLayer = import(".RuleLayer")
local BatmanSubLayer = class(“BatmanSubLayer”, RuleLayer)
function BatmanSubLayer:ctor(…)
self.super.ctor(self)
self.circleCount = 1
end

return BatmanSubLayer

最后写一个BatmanHuZi继承自BatmanSubLayer的类
local BatmanSubLayer = import(".BatmanSubLayer")
local BatmanHuZi = class(“BatmanHuZi”, BatmanSubLayer)
function BatmanHuZi:ctor(…)
self.super.ctor(self)
end

return BatmanHuZi

在使用BatmanHuZi的时候出现如下崩溃日志
Cocos2d:
stack traceback:
: in function ‘__index’
:36: in function ‘ctor’
:36: in function ‘ctor’
:36: in function ‘ctor’
:36: in function ‘ctor’
:36: in function ‘ctor’
:36: in function ‘ctor’
:36: in function ‘ctor’
:36: in funct

然后我考虑是
function BatmanHuZi:ctor(…)
self.super.ctor(self.super)
end
中得self传到父类时其实就是子类自己,所以父类BatmanSubLayer再次调用的时候仍然调用的是他自己的方法就会陷入死循环,出现内存溢出
于是我把BatmanSubLayer,BatmanHuZi更改如下
local RuleLayer = import(".RuleLayer")
local BatmanSubLayer = class(“BatmanSubLayer”, RuleLayer)
function BatmanSubLayer:ctor(…)
self.super.ctor(self.super)
self.circleCount = 1
end

return BatmanSubLayer

local BatmanSubLayer = import(".BatmanSubLayer")
local BatmanHuZi = class(“BatmanHuZi”, BatmanSubLayer)
function BatmanHuZi:ctor(…)
self.super.ctor(self.super)
end

return BatmanHuZi
但是这个时候在调用到RuleLayer的时候self就会出现nil的问题,日志如下
Cocos2d: LUA ERROR: :22: attempt to call method ‘setNodeEventEnabled’ (a nil value)

Cocos2d:
stack traceback:
:22: in function ‘ctor’
:37: in function ‘ctor’
: in function ‘new’
:141: in function ‘initRuleViews’
:92: in function ‘ctor’
: in function ‘new’
: in function ‘enterScene’
:106: in function ‘switchScene’
string "/Users/admin/Documents/work/freedom/projects/scripts/app/views/Home …
哪位前辈处理过相关问题,请求指点一二,先谢谢了!!!

找到了作如下改动就可以了
local RuleLayer = import(".RuleLayer")
local BatmanSubLayer = class(“BatmanSubLayer”, RuleLayer)
function BatmanSubLayer:ctor(…)
BatmanSubLayer.super.ctor(self.super)
self.circleCount = 1
end

return BatmanSubLayer

local BatmanSubLayer = import(".BatmanSubLayer")
local BatmanHuZi = class(“BatmanHuZi”, BatmanSubLayer)
function BatmanHuZi:ctor(…)
BatmanHuZi.super.ctor(self.super)
end

return BatmanHuZi

找到了作如下改动就可以了
local RuleLayer = import(".RuleLayer")
local BatmanSubLayer = class(“BatmanSubLayer”, RuleLayer)
function BatmanSubLayer:ctor(…)
BatmanSubLayer.super.ctor(self.super)
self.circleCount = 1
end

return BatmanSubLayer

local BatmanSubLayer = import(".BatmanSubLayer")
local BatmanHuZi = class(“BatmanHuZi”, BatmanSubLayer)
function BatmanHuZi:ctor(…)
BatmanHuZi.super.ctor(self.super)
end

return BatmanHuZi

是的,要好好理解这里的继承。和下面这个遇到的其实是一样的:
http://www.cocoachina.com/bbs/read.php?tid=215010&fpage=4

感谢楼主分享,解决了困惑我的问题