cocos2d-x 2.2.0 控制lua指令碼載入時的搜尋路徑
阿新 • • 發佈:2019-02-08
在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