转载地址:http://geekgaoyang.herokuapp.com/blog/2015/02/11/cocos2d-x-tutorial-of-binding-c-plus-plus-class-to-lua-usage/
本篇博文主要记录一下 C++ 如何绑定一个类到 Lua
一、先决条件
- 1、Python 使用brew包管理器安装 Python
1
2
3
| sudo easy_install pip
sudo pip install PyYAML
sudo pip install Cheetah |
- 3、ndk-r9b-x86_64 修改 .bash_profile 设置环境变量
1
| export NDK_ROOT=/path/to/android-ndk-r9b |
- 4、进入到 cocos2d-x/tools/tolua
以上执行成功说明 lua 绑定所需要的环境配置 ok
二、开始绑定自定义类
Custom.h
1
2
3
4
5
6
7
8
9
10
11
12
13
| #ifndef __MyLuaGame__Custom__
#define __MyLuaGame__Custom__
#include "cocos2d.h"
class Custom : cocos2d::Ref{
public:
CREATE_FUNC(Custom)
virtual bool init();
void test();
};
#endif /* defined(__MyLuaGame__Custom__) */
|
Custom.cpp
1
2
3
4
5
6
7
8
9
10
11
12
| #include "Custom.h"
#include <stdio.h>
bool Custom::init()
{
return true;
}
void Custom::test()
{
printf("hello world\n");
}
|
拷贝一份 cocos2dx.ini 重命名为 cocos2dx_custom.ini
cocos2dx_custom.ini
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| 搜索: [cocos2d-x]
替换: [cocos2dx_custom]
搜索: prefix = cocos2dx
替换: prefix = cocos2dx_custom
搜索: target_namespace = cc
替换: target_namespace =
搜索: headers = ...
替换: headers = %(cocosdir)s/../runtime-src/Classes/Custom.h
搜索: classes = ...
替换: classes = Custom
搜索: skip = ...
替换: skip =
搜索: rename_functions = ...
替换: rename_functions =
搜索: rename_classes = ...
替换: rename_classes =
|
- 3、修改 genbindings_custom.py
拷贝一份 genbindings.py 重命名为 genbindings_custom.py
genbindings_custom.py
1
2
3
4
| 搜索: output_dir = '%s/cocos/scripting/lua-bindings/auto' % project_root
替换: output_dir = '%s/../runtime-src/Classes/auto' % project_root
搜索: cmd_args = ...
替换: cmd_args = {'cocos2dx_custom.ini' : ('cocos2dx_custom', 'lua_cocos2dx_custom_auto')}
|
打开终端,执行绑定脚本,注意查看终端有没有失败的信息!!!
执行
1
| ./genbindings_custom.py
|
如果以上执行成功,在 Classes 目录下会生成一个 auto 文件夹,里面是生成的绑定文件
三、 Lua 中调用 C++ 类
- 1、增加绑定代码到 Xcode 并在 AppDelegate 中添加注册代码
AppDelegate.cpp
1
2
3
4
5
6
7
8
9
10
| ...
#include "lua_cocos2dx_custom_auto.hpp"
...
bool AppDelegate::applicationDidFinishLaunching()
{
...
register_all_cocos2dx_custom(L);
...
}
|
main.lua
1
2
| local custom = Custom:create()
custom:test()
|
控制台