cocos2d-x - C++/Lua交互

时间:2022-06-29 20:58:53

使用tolua++将自定义的C++类嵌入,让lua脚本使用

一般过程:

自定义类 -> 使用tolua++工具编译到LuaCoco2d.cpp中 -> lua调用

步骤一:自定义一个C++类,我定义一个类名为:MySprite

MySprite.h

cocos2d-x - C++/Lua交互

MySprite.cpp

cocos2d-x - C++/Lua交互

步骤二:根据自定义类创建一个.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++的工具,如图:

cocos2d-x - C++/Lua交互

解压出工具后,我们在配置tolua++的路径,用Xcode打开build.sh文件,更改俩个地方:

cocos2d-x - C++/Lua交互

更改后根据各台电脑路径不一,我更改后为:

cocos2d-x - C++/Lua交互

在这里TOLUA是tolua++工具的位置(路径后加上/tolua++,表示此工具),下面配置的是编译后LuaCocos2d.cpp文件导出的位置

最后,我们将定义的.pkg文件注册到tolua++文件夹下的Cocos2d.pkg中

cocos2d-x - C++/Lua交互

以上都做完后,我们直接使用终端,到tolua++文件夹下,使用make命令执行tolua++工具

OK!   执行完命令后,将会在桌面上生成LuaCocos2d.cpp文件,且其中已binding好了自定义的类

将新生成的LuaCocos2d.cpp替换掉我们生成项目里的LuaCocos2d.cpp文件

注意:这时新生成的LuaCocos2d.cpp中虽然已经binding了我们的自定义类,但没有引用我们的头文件,这时我们在LuaCocos2d.h中倒入我们的自定义类名

步骤四:Lua中测试我们的自定义类

cocos2d-x - C++/Lua交互

保存,command + R,成功运行且调用自定义类:

cocos2d-x - C++/Lua交互