在cocos2dx-lua中对功能模块的管理ctrl

来源:互联网 发布:sql平均分大于80 编辑:程序博客网 时间:2024/04/28 06:04

<span style="font-family: 'Source Code Pro', monospace; white-space: pre-wrap; background-color: rgb(255, 255, 255);">   开发cocos2dx也有半年多啦,第一次来这个地方分享自己的思路代码,好紧张啊。  </span>

什么也别说,直接说思路吧!由于lua代码的特征性,可以写出很多特色的代码,就比如,现在我要说的,直接创建一个单例的代码块,我的是ModuleController,我的思路是获取每一个模块的代码

--[[
模块数组...
-- 模块的ctrl数据{[1]=ctrl的名字 ,[2]=ctrl的路径 ,[3]=功能对应的资源plist}--
-- ]]MODULE_NAME ={    xxCtrl = {[1] = "xxCtrl", [2] = "game/xxx/xxx", [3] = "xxx.plist"}
}<pre name="code" class="plain">--获取模块function ModuleController:getModuleByName(module)    local module_name = module[1]    if _G[module_name] and _G[module_name]["getInstance"] then --已经require的模块        return _G[module_name]:getInstance()    elseif not _G[module_name] and module[2] then --还没有        require (module[2])        return self:getModuleByName(module)    endend

这个地方传入的模块就是刚刚数组里面的<span style="font-family: Arial, Helvetica, sans-serif;">{[1] = "xxCtrl", [2] = "game/xxx/xxx", [3] = "xxx.plist"},这个方法好处就是一个ctrl就是一个功能模块,然后相关功能的代码可以统一在ctrl里面require,那么刚刚的方法就可以,什么时候使用到代码,什么时候require咯</span>
<span style="font-family: Arial, Helvetica, sans-serif;"></span>
<span style="font-family: Arial, Helvetica, sans-serif;">第二步,我从取到的模块里面去取使用的方法</span>
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="plain">--[[打开ctrl中的方法-- @param module_name 模块名字-- @param is_loading  是否要预加载资源-- @param func_name   执行模块的方法-- @param ...         方法参数-- ]]function ModuleController:callFuncByModule(module, is_loading, func_name, ...)    if is_loading == true and module then --先加载plist吧        local info = module        if isFileExist(info[3]) then --这个是关于判断这个文件是不是存在的(cocos2dx已经提供啦)            cc.SpriteFrameCache:getInstance():addSpriteFrames(info[3])        else            print("警告:"..info[3].." 不存在!!!")        end    end    --获取模块    local moduleCtrl = self:getModuleByName(module)    if moduleCtrl and moduleCtrl[func_name] then        return moduleCtrl[func_name](moduleCtrl, ...)    endend

那么如此一个我觉得不错的lua模块管理器就不错啦,有什么好的也可以给出建议




0 0
原创粉丝点击