这里将介绍使用tolua++将自定义的C++类嵌入,让lua脚本使用
一般过程:
自定义类 -> 使用tolua++工具编译到LuaCoco2d.cpp中 -> lua调用
步骤一:自定义一个C++类,我定义一个类名为:MySprite
MySprite.h
MySprite.cpp
步骤二:根据自定义类创建一个.pkg文件,我们把自定义的MySprite类定义到.pkg文件中
注意:1>,只要根据自定类.h中的内容,至于.cpp的实现,binding后lua会自动调用类的函数
2>,书写.pkg文件时要注意几条规则,我们到tolua++文件夹中找到README文件
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
这里有.pkg文件详细的书写规则
我们这里直接写一个MySprite.pkg文件,内容如下:
class MySprite : public CCSprite{
static MySprite * createMS(const char * fileName);
}
书写好我们的.pkg文件之后,将文件放入tolua++文件夹下就可以了
步骤三:配置tolua++工具,用tolua++编译我们写的.pkg文件,将自定义类嵌入到LuaCocos2d.cpp中
我们在tolua++文件夹下找到tolua++.Mac.zip文件,并解压它得到一个tolua++的工具,如图: