cocos2d-x 2.2.0 控制lua脚本加载时的搜索路径

原文链接:http://segmentfault.com/blog/mituba/1190000000454114


在lua语言中,require语句搜寻模块有一个内置的顺序,并且可以通过package.path来维护模块的搜索策略。
但是在cocos2d-x中,不是这样!

cocos2d-x重载了原本的lua的require加载方式。(见Cocos2dxLuaLoader.cpp )
Cocos2dxLuaLoader逻辑的生效是在package.path之前,并且package.path在安卓上则不能很好的处理加载pkg包内部文件的问题。
所以在实际使用中,我们只使用cocos2d-x重载的方法就可以了。

怎么做呢?

Cocos2dxLuaLoader内部是使用CCFileUtils::getFileData()来加载lua代码的。
所以我们要想添加自己的lua脚本搜索路径,那么只要调用CCFileUtils::addSearchPath()就可以了。

以下C++代码实现了在iOS和android平台上,程序先从下载路径下的scripts文件夹寻找lua文件,再从程序内置资源路径下的scripts文件夹寻找lua文件的目标。

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    std::string downloadedScriptPath = CCFileUtils::sharedFileUtils()->getWritablePath() + "scripts";
    CCFileUtils::sharedFileUtils()->addSearchPath(downloadedScriptPath.c_str());
    std::string scriptPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("scripts");
    CCFileUtils::sharedFileUtils()->addSearchPath(scriptPath.c_str());
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    std::string downloadedScriptPath = CCFileUtils::sharedFileUtils()->getWritablePath() + "/scripts";
    CCFileUtils::sharedFileUtils()->addSearchPath(downloadedScriptPath.c_str());
    CCFileUtils::sharedFileUtils()->addSearchPath("assets/scripts");
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    //TODO
#else
    _ERROR_
#endif




相关文章

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