cocos2dx-3.4 lua import

本文详细介绍了从Cocos2d-x 2.x版本过渡到3.4版本时,Lua层遇到的一些挑战和解决方法,特别是关于class()和import()这两个常用且有趣的函数的使用。文章通过代码实例演示了如何通过import()函数进行模块加载,并解释了其如何获取外部调用处的目录位置。同时,文章还深入探讨了Lua中调试的概念和调试库的重要作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,v = debug.getlocal(3, 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的模块所在的文件位置。

好设计,精致啊。





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值