Lua附带了5.2版本的免费在线参考手册(我正在使用),也可以使用Lua中的5.0版编程.
然而,这些版本之间有一些变化,我似乎无法超越.这些更改在5.2和5.1参考手册的后续版本中有所说明.注意连续弃用有luaL_openlib()利于luaL_register(),然后luaL_register()赞成luaL_setfuncs().
网上搜索结果不一,其中大多数指向luaL_register().
我尝试实现的目标可以通过以下迷你程序进行总结,该程序可以编译并链接,例如, gcc ./main.c -llua -ldl -lm -o lua_test
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdio.h>
#include <string.h>
static int test_fun_1( lua_State * L )
{
printf( "t1 function fired\n" );
return 0;
}
int main ( void )
{
char buff[256];
lua_State * L;
int error;
printf( "Test starts.\n\n" );
L = luaL_newstate();
luaL_openlibs( L );
lua_register( L, "t1", test_fun_1 );
while ( fgets( buff, sizeof(buff), stdin ) != NULL)
{
if ( strcmp( buff, "q\n" ) == 0 )
{
break;
}
error = luaL_loadbuffer( L, buff, strlen(buff), "line" ) ||
lua_pcall( L, 0, 0, 0 );
if (error)
{
printf( "Test error: %s\n", lua_tostring( L, -1 ) );
lua_pop( L, 1 );
}
}
lua_close( L );
printf( "\n\nTest ended.\n" );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作,输入t1()产生预期的结果.
我现在想创建一个Lua可见的库/包.Lua中的Programming 建议我们使用数组和加载函数:
static int test_fun_2( lua_State * L )
{
printf( "t2 function fired\n" );
return 0;
}
static const struct luaL_Reg tlib_funcs [] =
{
{ "t2", test_fun_2 },
{ NULL, NULL } /* sentinel */
};
int luaopen_tlib ( lua_State * L )
{
luaL_openlib(L, "tlib", tlib_funcs, 0);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
然后使用luaopen_tlib()后luaL_openlibs().这样做允许我们在tlib:t2()定义时使用LUA_COMPAT_MODULE(在兼容模式下工作).
在Lua 5.2中这样做的正确方法是什么?
该luaopen_tlib函数应该以这样的方式编写:
int luaopen_tlib ( lua_State * L )
{
luaL_newlib(L, tlib_funcs);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
在main函数中,您应该像这样加载模块:
int main ( void )
{
// ...
luaL_requiref(L, "tlib", luaopen_tlib, 1);
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以{"tlib", luaopen_tlib}在loadedlibs表中添加条目linit.c.