在cocos2d-x+lua开发中,实现c++代码在lua脚本中调用是必不可少的(也就是所谓绑定c++到lua)。实现C++绑定有两种方式:1.通过.pkg文件2.通过直接写代码(.h/.cpp)文件绑定。
这次主要介绍通过自己写代码实现。cocos2d引擎本身是通过代码方式来实现lua绑定的。主要代码见:LuaCocos2d.h,LuaCocos2d.cpp两个文件,绑定入口见CCLuaEngine::init函数的tolua_Cocos2d_open(m_state);这一行。
为了简单说明绑定过程,贴出我自己测试的代码如下:
class TestLuaInterface
{
public:
static void staticPrint(constchar* msg);//需要在lua中调用该函数
};
//需定义如下函数
int tolua_TestLuaInterface_staticPrint(lua_State* L)
{
//从L中获取第2个参数,注意如果参数类型是通过自己扩展的,例如TestLuaInterface这个类型,需要使用tolua_tousertype()函数实现获取参数。
char* msg =(char*) tolua_tostring(L, 2, NULL);
if(msg)
{
TestLuaInterface::staticPrint(msg);//调用类型本身的函数
}
else
{
printf("msgis null");
}
return 1;
}
//注册lua接口
TOLUA_API int tolua_TestLuaInterface_open(lua_State* L)
{
tolua_open(L);
tolua_usertype(L, "TestLuaInterface");//注册用户自定义类型
tolua_module(L, NULL, 0);
tolua_beginmodule(L,NULL);
tolua_cclass(L, "TestLuaInterface","TestLuaInterface", "", NULL);
tolua_beginmodule(L,"TestLuaInterface");
//注册类的函数
tolua_function(L, "staticPrint",tolua_TestLuaInterface_staticPrint);
tolua_endmodule(L);
tolua_endmodule(L);
return 1;
}
//lua脚本
TestLuaInterface:staticPrint("hellofrom lua ")
在AppDelegate.cpp中调用注册函数实现注册:
tolua_TestLuaInterface_open(pEngine->getLuaState());
注意事项:
1.本例子中调用接口:int tolua_TestLuaInterface_staticPrint(lua_State* L)中获取lua脚本传递过来的参数是通过tolua_tostring()/tolua_tousertype()/…等函数实现的,需要根据参数类型来使用不同的函数获取相应的值,详细参见tolua_to.c文件。
2.注册lua接口时tolua_beginmodule(L,NULL)和tolua_endmodule(L);要成对出现。
3.Cocos2d-x中默认是不输出lua脚本的错误信息的,需要在LuaCocos2.h添加如下定义:
#define COCOS2D_DEBUG 1
这样在VC的输出窗口中就能看到脚本的错误信息(如果有的话),方便查找脚本错误。
4.本例子中调用结果是在控制台输出一句log,所以需要打开控制台:打开mani.cpp中的USE_WIN32_CONSOLE宏