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

转载地址: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 依赖包
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
1
./genbindings.py

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

二、开始绑定自定义类

  • 1、编写一个简单的 C++ 类
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");
}
  • 2、修改 cocos2dx_custom.ini

拷贝一份 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')}
  • 4、开始绑定

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

执行
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);
    ...
}
  • 2、在 Lua 中调用
main.lua
1
2
local custom = Custom:create()
custom:test()
  • 3、编译运行查看控制台输出
控制台
1
hello world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值