cocos2dx-3.4 lua import

cocos2dx版本号:3.4final

lua版本:5.2


从2.x切换到3.4,有几个不适应的地方,一个就是lua层进行的封。稍微研究了一下,发现2个方法是经常使用,而且是很有意思的,class() and import()。

class主要作用是进行继承,import毫无以为就是加载。

lua本身的模块加载是通过require来实现的。import其实只是对file_name进行了修改,最终依然是使用require进行修改。上代码


function import(moduleName,currentModuleName)
    local currentModuleNameParts
    local moduleFullName = moduleName
    local offset = 1

    while true do
        if string.byte(moduleName,offset) ~= 46 then -- .
            moduleFullName = string.sub(moduleName,offset)
            if currentModuleNameParts and #currentModuleNameParts > 0 then
                moduleFullName = table.concat(currentModuleNameParts,".") .. "." .. moduleFullName
            end
            break
        end
        offset = offset + 1

        if not currentModuleNameParts then
            if not currentModuleName then
                local n,v = debug.getlocal(3,1)
                currentModuleName = v
            end

            currentModuleNameParts = string.split(currentModuleName,".")
        end
        table.remove(currentModuleNameParts,#currentModuleNameParts)
    end

    return require(moduleFullName)
end

import(".abc") -- require(app.models.abc)

import("..abc") -- require(app.abc)

import("...abc") -- reuqire(abc)

import("....abc") -- requier(abc)

ps:import所在目录是 src/app/models/test.lua

结论:.代表上层目录

ok我们在看一下import是如何获取外面调用处所在的目录?

在这里

local n,1)
print(n,v)打印结果 : (*temporary) app.models.test

在说说debug吧,lua本身不提供调试器,但是提供了编写调试器所需的原语句。调试库有一个重要的概念 “栈层 (stake level)”,一个栈层表示一个数字,即一个已被调用尚未返回的函数调用调试库函数的层级是1,调用函数函数层级是2,以此类推。

debug.getlocal检查任意活动函数的局部变量。变量1是函数层级即栈层,2是变量索引。变量索引为一个数字,根据变量出现的先后顺序由1开始递增。

我们就集齐了7颗龙珠,可以召唤神龙了。不过还是要屡一下。

lua模块加载通过require加载,import 本身栈层1 -》上层import调用处2 -》在上层,一定是require,栈层3 -》在在上层,可能是import...

所以取栈层为3,所以为1的参数,自然取到了调用import的模块所在的文件位置。

好设计,精致啊。

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...