簡體   English   中英

嵌入Lua 5.2並定義庫

[英]Embedding Lua 5.2 and defining libraries

Lua附帶了5.2版本的免費在線參考手冊 (我正在使用),也可以使用Lua中的5.0版編程

然而,這些版本之間有一些變化,我似乎無法超越。 這些更改在5.25.1參考手冊的后續版本中有所說明。 注意luaL_openlib()的連續棄用有利於luaL_register() ,然后luaL_register()有利於luaL_setfuncs()

Web上的搜索結果不一,其中大多數都指向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可見的庫/包。 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;
}

然后在luaopen_tlib()之后使用luaL_openlibs() 如果我們定義LUA_COMPAT_MODULE (在兼容模式下工作tlib:t2()這樣做允許我們使用tlib:t2() )。

在Lua 5.2中這樣做的正確方法是什么?

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM