转发,请保持地址:http://blog.youkuaiyun.com/stalendp/article/details/8920018
在cocos2dx中使用lua进行开发的过程中,肯定会涉及到对lua功能进行扩充的情况,网络上已经有相关的文章,不过不是那么简单明了。所以我这里特意写了这篇文章,也是作为自己学习的一个总结吧。这里我将使用Eclipse来开发lua。使用eclipse开发lua,可以运用其强大的扩展能力,大大地加快开发。文章将介绍怎么定制一个工具来生成lua,并进行调用。
开发工具下载
使eclipse开发lua有两种方法: 1)安装ldt; 2)下载整合好的eclipse;
ldt的安装就不介绍了,大家可以到网上去搜索关于eclipse插件安装的教程;官方也有相应的说明:http://www.eclipse.org/koneki/ldt/#documentation
如果要安装c++相关的功能,还需要安装cdt,cdt的官方如下:http://www.eclipse.org/cdt/downloads.php
工程的创建
配置toLua++工具
整合开发
#ifndef LuaTest01_MyTest_h
#define LuaTest01_MyTest_h
#include "cocos2d.h"
USING_NS_CC;
class MyTest: public CCLayer {
private:
int invokeHandler;
public:
MyTest() : invokeHandler(0) {}
CREATE_FUNC(MyTest);
void setHandler(int _handler) {
this->invokeHandler = _handler;
}
void callFunc() {
CCLuaStack* pStack = CCLuaEngine::defaultEngine()->getLuaStack();
pStack->pushInt(123);
pStack->executeFunctionByHandler(this->invokeHandler, 1);
}
void sayHello() {
CCLog("Hello, world!");
}
static void classInfo() {
CCLog("This class is MyTest");
}
void otherFunc() {
//This function doesn't expose to the lua
}
};
#endif
class MyTest: public CCLayer {
static MyTest* create();
void setHandler(LUA_FUNCTION _handler) ;
void callFunc() ;
void sayHello() ;
static void classInfo() ;
};
#include "MyTest.h"
/* Exported function */
TOLUA_API int tolua_MyTest_open (lua_State* tolua_S);
并在MyTest.h中引入下面的头文件:
extern "C" {
#include "tolua++.h"
#include "tolua_fix.h"
}
#include "CCLuaEngine.h"
tolua_MyTest_open(pEngine->getLuaStack()->getLuaState());
cclog("====test static method=====");
MyTest:classInfo();
cclog("====test member function========");
local mt = MyTest:create();
mt:sayHello();
cclog("====test callback function=====");
local function callback(num)
cclog("This is the function from lua, and param is: " .. num);
end
mt:setHandler(callback);
mt:callFunc();
结果如下: