cocos2d-x 中使用tolua++来导入自己编写的C++ 类

cocos2d-x版本:2.2.1

系统:os x 10.8.5

编译器:xcode 5.0.2

首先先自己新建一个类:

.h

class TestClass
{
    int a_, b_;
public:
    static TestClass* create(); // tolua++ 会吧构建函数解释为new函数,析构函数为delete函数
    void SetA(int a);
    void SetB(int b);
    int GetSum();
};
.cpp

void TestClass::SetA(int a)
{
    a_ = a;
}
void TestClass::SetB(int b)
{
    b_ = b;
}

int TestClass::GetSum()
{
    return a_ + b_;
}

TestClass* TestClass::create()
{
    return new TestClass();
}

在使用tolua++之前我们需要编写一个类的说明文件(pkg),下面是编写规则

  1) enum keeps the same     //枚举类型保留不变

   2) remove CC_DLL for the class defines, pay attention to multi inherites      //不要使用CC_DLL,改用多继承

   3) remove inline keyword for declaration and implementation               //删除内置变量?

   4) remove public protect and private    //不要用访问限定词

   5) remove the decalration of class member variable  //不要成员变量(public的变量可以保留)

   6) keep static keyword        //保留静态关键词

   7) remove memeber functions that declared as private or protected//public的函数都删除

然后编写TestClass.pkg:

class TestClass
{
    void SetA(int a);
    void SetB(int b);
    int GetSum();
    static TestClass* create(); // 保留静态关键词
};

除了编写导入类的pkg文件以外我们还需要把TestClass.pkg文件配置到Cocos2d.pkg文件中,不过在这之前我们先看下Cocos2d.pkg的文件:

$#include "LuaCocos2d.h"

$pfile "matrix.pkg"
$pfile "ccTypes.pkg"
$pfile "CCObject.pkg"
$pfile "CCCommon.pkg"
$pfile "CCGeometry.pkg"
$pfile "CCArray.pkg"
我们可以看出$#include 是用来导入头文件的饿,$pfile是用来导入pkg文件的,因而我们需要添加

$#include "TestClass.h"
$pfile "TestClass.pkg"
#其实$后面的东西会不做改变的复制到LuaCocos2d.cpp中,不过$pfile是怎么一回事我就真的不知道了啊。。。。。。。
到Cocos2d.pkg中,好了现在开始使用tolua++来自动生成C++类的Lua的使用接口了;

不过还需要配置一下build.sh中的tolua++的路径,我的tolua++与build.sh在同一目录,所以配置为:

#!/bin/bash
#
# Invoked build.xml, overriding the lolua++ property

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
TOLUA="./tolua++"
if [ -z "${TOLUA}" ]; then
    TOLUA=`tolua++`
fi

if [ -z "${TOLUA}" ]; then
    echo "Unable to find tolua++ (or tolua++5.1) in your PATH."
    exit 1
fi

cd ${SCRIPT_DIR}
${TOLUA} -L basic.lua -o ../../scripting/lua/cocos2dx_support/LuaCocos2d.cpp Cocos2d.pkg
现在可以直接运行了:

./build.sh	



你可能感兴趣的:(cocos2d-x,tolua++)