在用cocos2d-x的时候已经用过tolua++了,今天有心情就下了源码包来试一试。
tolua++的编译可以很容易在vs上搞定,写pkg什么的从来都觉得不那么顺手,于是参考了一下cocos项目的使用。将tolua++-1.0.93\src\lib里面的源文件加上一个tolua++-1.0.93\include里的tolua++.h拿出来,放到自己的工程下就好了,要打包成lib、dll、so什么的话其实没必要,因为这几个文件的代码量很小,五十多k那样。
没用到tolua++的时候,就先试一试简单的跟lua交互
lua文件 ding.lua 只有一行 ding = 7777
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include <stdio.h>
#define FILE_NAME "ding.lua"
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
int err = luaL_dofile(L, FILE_NAME);
lua_getglobal(L, "ding");
int num = lua_tonumber(L, -1);
printf("ding: %d\n", num);
lua_close(L);
getchar();
return 0;
}
使用tolua++之后cpp文件加了一段
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include <stdio.h>
// ===========================================
#include "tolua++.h"
class MyClass
{
public:
void hello(const char* str){printf("MyClass: %s\n", str);};
};
static int hello(lua_State* tolua_S)
{
const char* str = tolua_tostring(tolua_S, 1, 0);
MyClass ins;
ins.hello(str);
tolua_pushstring(tolua_S, "ok");
return 1;
}
TOLUA_API int tolua_Classes_open(lua_State* tolua_S);
TOLUA_API int tolua_Classes_open(lua_State* L)
{
tolua_open(L);
tolua_usertype(L, "MyClass");
tolua_module(L, NULL, 0);
tolua_beginmodule(L, NULL);
tolua_cclass(L, "MyClass", "MyClass", "", NULL);
tolua_beginmodule(L, "MyClass");
tolua_function(L, "hello", hello);
tolua_endmodule(L);
tolua_endmodule(L); // lua state
return 1;
}
// ===========================================
#define FILE_NAME "ding.lua"
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
tolua_Classes_open(L);
int err = luaL_dofile(L, FILE_NAME);
lua_getglobal(L, "ding");
int num = lua_tonumber(L, -1);
printf("ding: %d\n", num);
lua_close(L);
getchar();
return 0;
}
这时可以写个长一点的脚本看看
ding = 7777
-- new error handler
local function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end
local function main()
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
print("just trying")
print("lua: "..MyClass.hello("this is lua"))
--~ print("lua: "..hello("this is lua"))
end
xpcall(main, __G__TRACKBACK__)
调用tolua++的api就可以给lua暴露一些自定义的函数,更重要的是我们自定义的类,对于每一个需要暴露的类成员函数也是需要定义一个跟lua交互的函数。这里交互的函数为static int hello(lua_State* tolua_S)。 跟lua_CFunction 的类型要一致,其实不用tolua++也是可以的,可以自己使用lua本来自带的一些东西来写,不过那样会涉及比较多stack的问题。以前得为前辈说过,如果有一些第三方库可以直接用就用它,不必什么都自己写,而且大多第三方库更加稳定,可能出现的问题绝对比自己写要少。