原帖地址 http://www.cnblogs.com/linchaolong/p/4033133.html
tolua++简介
tolua++工具所在目录:cocos2d-x-2.2.1\tools\tolua++, 在目录下有一个README文件,打开有关于这个工具的介绍与使用说明。
通过使用该命令生成绑定文件 :tolua++.exe -L basic.lua -o LuaCocos2d.cpp Cocos2d.pkg,新生成的LuaCocos2d.cpp文件将会覆盖旧的。
LuaCococs2d.cpp文件所在路径:cocos2d-x-2.2.1\scripting\lua\cocos2dx_support。
在LuaCocos2d.cpp文件中完成我们自定义类的注册,然后才能在Lua中使用我们C++中的自定义类。
自定义类
类声明如下:SpriteFactory.h
[cpp] view plaincopyprint?
#ifndef _SPRITE_FACTORY_H_
#define _SPRITE_FACTORY_H_
#include "cocos2d.h"
USING_NS_CC;
class SpriteFactory{
public:
static void createSprite(CCLayer* layer);
};
#endif
类实现如下:SpriteFactory.cpp
[cpp] view plaincopyprint?
#include "SpriteFactory.h"
void SpriteFactory::createSprite(CCLayer* layer){
//创建一个CCLayerColor
CCLayer* addLayer = CCLayerColor::create(ccc4(200,100,100,255));
addLayer->setContentSize(CCSizeMake(layer->getContentSize().width/2,layer->getContentSize().height/2));
addLayer->setPosition(ccp(layer->getContentSize().width/2,layer->getContentSize().height/2));
//添加到目标Layer
layer->addChild(addLayer);
}
编写pkg文件
pkg文件的编写,需要遵循以下规则:
2. Writing .pkg files
1) enum keeps the same 保持枚举类型值的定义
2) remove CC_DLL for the class defines, pay attention to multi inherites 不要使用CC_DLL(点击查看CC_DLL详细解释),使用多继承代替
3) remove inline keyword for declaration and implementation 在声明和实现中移除inline关键字
4) remove public protect and private 移除public、protect和private关键字
5) remove the decalration of class member variable 移除类成员变量的定义
6) keep static keyword 保持static关键字
7) remove memeber functions that declared as private or protected 移除那些声明为private或者protected的成员函数
pkg文件内容如下:SpriteFactory.pkg
[plain] view plaincopyprint?
class SpriteFactory{
static void createSprite(CCLayer* layer);
};
编写好的pkg文件放到tolua++.exe目录下。
使用tolua++生成LuaCocos2d.cpp
在LuaCocos2d.cpp中包含自定义类的头文件
自动生成的LuaCocos2d.cpp文件中目前还没有包含我们自定义类的头文件,所以会编译会报错,需要手动在LuaCocos2d.cpp文件中包含自定义类的头文件
打开liblua项目cocos2dx_support目录下的LuaCocos2d.cpp文件,添加自定义类的头文件
在包括头文件的时候,我们可能会遇到 " Error: 无法打开源文件 "的情况,解决办法如下:
右键liblua,选择属性—配置属性—C/C++目录—常规,在附加包含目录里添加我们自定义类文件所在目录,用";"隔开,最后点击确定,错误就消失了
注意:
1.在添加包含目录时,建议使用相对路径,如:$(ProjectDir)..\..\..\..\Classes\ui;($ProjectDir表示当前工程liblua的根目录)
2.附加包含目录必须是目标头文件所在目录,不可以是其父目录
在Lua中使用C++自定义类
这里我就直接在cocos2d-x lua项目Resource目录下的hello.lua脚本中使用自定义的SpriteFactory,在背景层上添加一个宽高为该背景层一半的CCLayerColor
注意,pkg文件的编码不能用UTF8格式,否则会编译错误
运行效果: