嵌入Lua 5.2并定义库。

Lua自带版本5.2的免费在线参考手册(我正在使用)和版本5.0的Programming in Lua也可用。然而,这些版本之间有一些我似乎无法超越的变化。这些变化在5.25.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;
 }

这样可以按预期工作,输入t1()会产生期望的结果。现在,我想创建一个对Lua可见的库/包。Programming in Lua建议我们使用一个数组和一个加载函数:

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;
}

然后在luaL_openlibs()后使用luaopen_tlib()。这样做允许我们使用tlib:t2(),如果我们定义了LUA_COMPAT_MODULE(在兼容模式下工作)。在Lua 5.2中,做到这一点的正确方法是什么?

点赞
用户1008957
用户1008957

luaopen_tlib 函数应该这样写:

int luaopen_tlib ( lua_State * L )
{
  luaL_newlib(L, tlib_funcs);
  return 1;
}

而在 main 函数中,你应该像这样加载该模块:

int main ( void )
{
    // ...
    luaL_requiref(L, "tlib", luaopen_tlib, 1);
    // ...
}

或者你可以在 linit.cloadedlibs 表中添加一个条目 {"tlib", luaopen_tlib}

2012-11-18 19:50:22