您的位置:首页 > 移动开发 > Cocos引擎

Cocos2d-x Tutorial 之 如何绑定 C++ 类到 Lua

2015-04-15 18:35 274 查看
转载地址: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

brew install python

2、Python 依赖包
12
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
1

./genbindings.py

以上执行成功说明 lua 绑定所需要的环境配置 ok


二、开始绑定自定义类

1、编写一个简单的 C++ 类Custom.h
12
3
4
5
6
7
8
9
10
1112
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
12
3
4
5
6
7
8
9
10
1112

#include "Custom.h"
#include <stdio.h>

bool Custom::init()
{
return true;
}

void Custom::test()
{
printf("hello world\n");
}

2、修改 cocos2dx_custom.ini拷贝一份 cocos2dx.ini 重命名为 cocos2dx_custom.ini
cocos2dx_custom.ini
12
3
4
5
6
7
8
9
10
1112
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
12
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')}

4、开始绑定打开终端,执行绑定脚本,注意查看终端有没有失败的信息!!!
执行
1

./genbindings_custom.py

如果以上执行成功,在 Classes 目录下会生成一个 auto 文件夹,里面是生成的绑定文件


三、 Lua 中调用 C++ 类

1、增加绑定代码到 Xcode 并在 AppDelegate 中添加注册代码AppDelegate.cpp
12
3
4
5
6
7
8
9
10

...
#include "lua_cocos2dx_custom_auto.hpp"
...

bool AppDelegate::applicationDidFinishLaunching()
{
...
register_all_cocos2dx_custom(L);
...
}

2、在 Lua 中调用main.lua
12

local custom = Custom:create()
custom:test()

3、编译运行查看控制台输出控制台
1

hello world


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: