2012-11-18 47 views
5

Lua自帶在線版本reference manual版本5.2(我正在使用)和Programming in Lua版本5.0也可用。嵌入Lua 5.2並定義庫

然而,這些版本之間有一些變化,我似乎無法超越。這些更改在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 建議我們to use陣列和負載功能:

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中做這件事的正確方法是什麼?

回答

8

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); 
    // ... 
} 

或者,您可以添加一個條目{"tlib", luaopen_tlib}linit.cloadedlibs表。

+0

luaL_openlibs是可選的,可能不應該在那裏(例如)。 – Cubic

+0

我編輯了示例,以便只顯示重要的行。 – prapin