Opening a CCScene in Lua from a C++ CCScene in cocos2d-x

Opening a CCScene in Lua from a C++ CCScene in cocos2d-x
0.0 0


I’m trying to use Lua scripting and Cocos2d-x together and I’m having a bit of trouble making things work properly.

Part 1: I have two CCScene classes, HomeScene and GameScene. HomeScene is written in C++ while GameScene is written in Lua Script. Now what I want to do is to create a ‘link’ between these two scenes. At a certain point in the life of HomeScene, it will create GameScene and GameScene will replace HomeScene (something like CCDirector::replaceScene). Then after that, during the life of GameScene, it returns back to HomeScene.

Part 2: Aside from that, HomeScene needs to pass some information, let’s say time, into GameScene. GameScene will then use this time value for further processing. When GameScene returns back to HomeScene, it passes yet another bit of data, let’s say score, back to HomeScene.

So, the question is, are both parts possible using Lua binding in cocos2d-x? If so, how should I go about implementing it?

What I’ve tried: I have created a small Lua script file to test if what I’m thinking can work.

local function main()
    local visibleSize = CCDirector:sharedDirector():getVisibleSize()
    local origin = CCDirector:sharedDirector():getVisibleOrigin()

    local function createLayer()
        local function doGoBack()

        local layer = CCLayer:create()

        local btn = CCMenuItemImage:create( "btn0.jpg", "btn1.jpg" )
        btn:setPosition( ccp( visibleSize.width * 0.50, visibleSize.height * 0.50 ) )
        btn:registerScriptTapHandler( doGoBack )

        local menu = CCMenu:createWithItem( btn )
        menu:setPosition( ccp( 0, 0 ) )
        layer:addChild( menu, 1 )

        cclog( "createdLayer" )

        return layer

    -- run
    local sceneGame = CCScene:create()
    sceneGame:addChild( createLayer() )
    CCDirector:sharedDirector():pushScene( sceneGame )

Then I created a CCScene that will call this script

void TestScene::runLuaScript() {
    std::string luaPath = CCFileUtils::sharedFileUtils() -> fullPathForFilename( "test.lua" );
    CCString * luaCode = CCString::createWithContentsOfFile( luaPath.c_str() );
    CCLuaEngine::defaultEngine() -> executeString( luaCode -> getCString() );

When I tried to run it, the Lua script is executed properly (the cclog output is properly printed) but the objects on the Lua scene is not visible and only a black screen appears (because TestScene is an empty scene).

I’m feeling what I’m thinking is possible, it’s just that I am implementing it wrong. Any help will be greatly appreciated. Thank you very much.


yeah, I am thinking about the similiar thing, but not got answer yet!