HongChow
HongChow

Reputation: 21

cocos2d-x run a lua script twice

I am developing a cocos2d-x app. The app starts with the main scene written in C++. And the main scene would create a logic scene written in lua. Here are the code in main scene:

void CMainSceneLayer::menuSelectedCallBack(cocos2d::CCObject * pSender)
{
    std::string scriptFile = "luaScripts/LogicScene.lua";
    scriptFile = CCFileUtils::sharedFileUtils()->fullPathForFilename(scriptFile.c_str());
    CCLog("scriptFile: %s\n", scriptFile.c_str());
    CCLuaEngine::defaultEngine()->executeScriptFile(scriptFile.c_str());
}

The following case is running the app in An android phone

When it runs "LogicScene.lua", everything goes well as expected. When it returns from Logic scene to MainScene, it gos well, too. But when the main scene tries to run "LogicScene.lua" again, nothing happens. It just remains in the main scene. No logs go out from LogicScene.lua.

I tested it by writing a test.lua who just prints a log. when test.lua was run the first time by main scene, a log was shown in logCat. But when test.lua was run the second time and forth, nothing happened.

I googled this for thousands of times by using thousands of keywords, nothing helpful was found.

And amazingly, everythings goes fine when I test it on Windows.

PS,On android set, all scripts are placed in "assets/luaScripts/" and LogicScene.lua requires some other lua scripts in "assets/luaScripts/".

And on windows, all scripts are placed in "Resources/luaScripts/"

What's going wrong? Can anyone help?

Upvotes: 0

Views: 866

Answers (1)

HongChow
HongChow

Reputation: 21

I've found the solution for this problem.

For the android version,

CCLuaEngine::defaultEngine()->executeScriptFile(arg) it use require statement to execute arg.

so when CCLuaEngine::defaultEngine()->executeScriptFile was called on the same lua file the second time or forth, nothing will happen.

I modified the source file in lua/cocos2dx_support/CCLuaStack.cpp to fix this problem.

Here I paste codes of my solution:

int CCLuaStack::executeScriptFile(const char* filename)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    //std::string code("require \""); //origin code
    std::string code(std::string("package.loaded[\"") + std::string(filename) + std::string("\"] = nil\n")); //this line was added by me
    code.append("require \"");
    code.append(filename);
    code.append("\"");
    return executeString(code.c_str());
#else
//more codes...
}

Upvotes: 2

Related Questions