一直想學學cocos2dx中如何使用tolua++工具使得lua腳本調用C++函數,今天就來搞一下,順便記錄下來:windows
首先,咱們打開cocos2dx-2.2.4中projects下的test的VS工程,能夠看到這個例子裏面已經有一個HelloWorld的類,咱們就用它來講明一下。ide
而後,咱們照着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++ui
Build scripts for windows (build.bat) and unix (build.sh) are providedlua
to generate the relevant files after modifying the .pkg files. Thesespa
scripts basically run the following command:unix
tolua++.exe -L basic.lua -o LuaCocos2d.cpp Cocos2d.pkgcode
This will generate the bindings file and patch it with come cocos2dxblog
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());
最後運行看看: