1、tolua测试
1.1、pkg文件的编写(1.pkg)
int test();
没错,我的例子就这么简单!
1.2、根据pkg文件生成cpp文件(注册接口用)
./tolua -o test.cpp 1.pkg
生成的test.cpp的代码如下:
/*
** Lua binding: 1
*/
#include "tolua.h"
#ifndef __cplusplus
#include <stdlib.h>
#endif
#ifdef __cplusplus
extern "C" int tolua_bnd_takeownership (lua_State* L); // from tolua_map.c
#else
int tolua_bnd_takeownership (lua_State* L); /* from tolua_map.c */
#endif
#include <string.h>
/* Exported function */
TOLUA_API int tolua_1_open (lua_State* tolua_S);
LUALIB_API int luaopen_1 (lua_State* tolua_S);
/* function to register type */
static void tolua_reg_types (lua_State* tolua_S)
{
}
/* function: test */
static int tolua_1_test00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isnoobj(tolua_S,1,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
int tolua_ret = (int) test();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'test'.",&tolua_err);
return 0;
#endif
}
/* Open lib function */
LUALIB_API int luaopen_1 (lua_State* tolua_S)
{
tolua_open(tolua_S);
tolua_reg_types(tolua_S);
tolua_module(tolua_S,NULL,0);
tolua_beginmodule(tolua_S,NULL);
tolua_function(tolua_S,"test",tolua_1_test00);
tolua_endmodule(tolua_S);
return 1;
}
/* Open tolua function */
TOLUA_API int tolua_1_open (lua_State* tolua_S)
{
lua_pushcfunction(tolua_S, luaopen_1);
lua_pushstring(tolua_S, "1");
lua_call(tolua_S, 1, 0);
return 1;
}
这样我们就成功的将test()这个函数注册给了lua
1.3 、增加main函数进行测试
int test()
{
return 6666;
}
int main()
{int tolua_tarray_open (lua_State*);
lua_State* L = luaL_newstate();
luaL_openlibs(L);
tolua_1_open(L);
luaL_dofile(L,"1.lua");
lua_close(L);
cout <<"hello world" << endl;
return 1;
}
编译命令为
g++ -c -g -ansi -Wall -g -I../../include -I/usr/local/include -o test.o test.cpp
g++ -g -ansi -Wall -g -I../../include -I/usr/local/include -o test test.o -L../../lib -L/usr/local/lib -ltolua -llua
注意:
如果编译的是cpp文件的时候包含lua头文件的时候要加上extern关键字
运行结果
-----------
6666
hello world
----------