cocos2dx中使用tolua++使lua調用c++函數


一直想學學cocos2dx中如何使用tolua++工具使得lua腳本調用C++函數,今天就來搞一下,順便記錄下來:

首先,我們打開cocos2dx-2.2.4中projects下的test的VS工程,可以看到這個例子里面已經有一個HelloWorld的類,我們就用它來說明一下。

然后,我們照着HelloWorld類的定義來寫pkg文件:

//MyClass.pkg

class HelloWorld : public cocos2d::CCLayer

{

      virtual bool init();

      static cocos2d::CCScene* scene();

      void menuCloseCallback(CCObject* pSender);

      static HelloWorld* create();

};

 

我們打開README文件可以看看書寫pkg文件的語法:

1. Generating the lua<-->C bindings with tolua++

    Build scripts for windows (build.bat) and unix (build.sh) are provided

    to generate the relevant files after modifying the .pkg files.  These

    scripts basically run the following command:

        tolua++.exe -L basic.lua -o LuaCocos2d.cpp Cocos2d.pkg

    This will generate the bindings file and patch it with come cocos2dx

    specific modifications.

    On POSIX systems you can also just run "make" to build the bindings

    if/when you change .pkg files.

2. Writing .pkg files

    1) enum keeps the same

    2) remove CC_DLL for the class defines, pay attention to multi inherites

    3) remove inline keyword for declaration and implementation

    4) remove public protect and private

    5) remove the decalration of class member variable

    6) keep static keyword

7) remove memeber functions that declared as private or protected

有一點還需要注意的是static cocos2d::CCScene* scene(); 這句話最好寫成static CCScene* scene();不然的話會出現下面這種錯誤:

error in function 'runWithScene'.

argument #2 is 'cocos2d::CCScene'; 'CCScene' expected.

原因我也不太清楚,按照錯誤提示替換掉就行了。

 

接着,我們把寫好的pkg文件放在tolua++目錄下,在cocos2d.pkg文件末尾添加$pfile "MyClass.pkg",點擊運行build.bat,這個文件主要是將cocos2d.pkg內包含的pkg文件整合生成LuaCocos2d.cpp,看下內部語法就知道了:

tolua++ -L basic.lua -o "../../scripting/lua/cocos2dx_support/LuaCocos2d.cpp" Cocos2d.pkg

然后,我們在LuaCocos2d.h中引入我們的HelloWorld的頭文件,在將lualib工程添加到該工程來,在該工程添加lua頭文件的引用,在鏈接其中添加lua51.lib和lualib.lib。

 

接下來我們添加一個lua腳本HelloWorld.lua,內容如下:

print("begin ...... ")

local director = CCDirector:sharedDirector()

local scene = HelloWorld:scene()

director:runWithScene(scene)

print("end ........ ")

 

在AppDelegate.cpp引入CCLuaEngine.h頭文件,代碼稍作如下修改:

//CCScene *pScene = HelloWorld::scene();

//pDirector->runWithScene(pScene);

CCScriptEngineProtocol* pEngine = CCLuaEngine::defaultEngine();

CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);

string fullpath = CCFileUtils::sharedFileUtils()->fullPathForFilename("HelloWorld.lua");

CCLuaEngine::defaultEngine()->executeScriptFile(fullpath.c_str());

 

最后運行看看:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM