cocos-Lua中的class与require机制

local layer = require("PaiGow.src.GamePlayerListLayer")

local GameTableUI = class("GameTableUI", require("gamemanager.GameViewBase"));

一开始,我是不懂加载某个类后是怎么传参数和怎么调用类里面的构造函数ctor的

一般我们加载其他类的时候是用require

这里说明一下: require函数

要加载一个模块,只需要简单地调用require “<模块名>”就可以了。这个调用会返回一个由模块函数组成的table,并且还会定义一个包含该table的全局变量。但是,这些行为都是由模块完成的,而非require。

所以,有些模块会选择返回其它值,或者具有其它的效果。

require会将返回值存储到table package.loaded中;如果加载器没有返回值,require就会返回table package.loaded中的值。可以看到,我们上面的代码中,模块没有返回值,而是直接将模块名赋值给table package.loaded了。这说明什么,package.loaded这个table中保存了已经加载的所有模块

require如何加载

1.先判断package.loaded这个table中有没有对应模块的信息;

2.如果有,就直接返回对应的模块,不再进行第二次加载;

3.如果没有,就加载,返回加载后的模块。

在C++中构造函数是在成员变量分配内存空间的时候来调用构造函数来初始化

在Lua中怎么说呢,其实它的做法是参照C++的,但相对来说,运用的的方法不一样

Lua中传参是运用create函数

local layer = require("PaiGow.src.GamePlayerListLayer"):create(self, self.tableLogic._deskUserList);

一般在声明类的时候

local GameResultLayer = class("GameResultLayer", require("ui.BaseLayer"));

定义了类名GameResultLayer,继承的ui.BaseLayer类

最重要的是在这个时候,它是运用了Lua中的function里面的class函数来声明

其中还说明了类中参数的传递与构造函数的调用

if not cls.ctor then

-- add default constructor

cls.ctor = function() end

end

cls.new = function(...)

local instance

if cls.__create then

instance = cls.__create(...)

else

instance = {}

end

setmetatableindex(instance, cls)

instance.class = cls

instance:ctor(...)

return instance

end

cls.create = function(_, ...)

return cls.new(...)

end

在我们require是运用create函数,其实就是调用cls.new(...),其中来使用instance:ctor(...)