加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2dx-3.4 lua import

发布时间:2020-12-14 20:33:32 所属栏目:百科 来源:网络整理
导读:cocos2dx版本号:3.4final lua版本:5.2 从2.x切换到3.4,有几个不适应的地方,一个就是lua层进行的封。稍微研究了一下,发现2个方法是经常使用,而且是很有意思的,class() and import()。 class主要作用是进行继承,import毫无以为就是加载。 lua本身的模

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的模块所在的文件位置。

好设计,精致啊。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读