【问题标题】:Lua c API - Add number to new libLua c API - 将数字添加到新库
【发布时间】:2018-03-13 00:42:36
【问题描述】:

(Lua 5.2)

我正在编写从 ncurses 到 Lua 的绑定,并且我想包含一些函数以外的值。我目前正在绑定这样的函数:

#define VERSION "0.1.0"

// Method implementation
static int example(lua_State* L){
    return 0;
}

// Register library using this array
static const luaL_Reg examplelib[] = {
    {"example", example},
    {NULL, NULL}
}

// Piece it all together
LUALIB_API int luaopen_libexample(lua_State* L){
    luaL_newlib(L, examplelib);
    lua_pushstring(L, VERSION);
    // Set global version string
    lua_setglobal(L, "_EXAMPLE_VERSION");
    return 1;
}

这会生成一个包含几个函数(在本例中只有一个)和一个全局字符串值的表,但我想在库中放置一个数字值。例如,现在lib = require("libexample"); 将返回一个带有一个函数example 的表,但我希望它也有一个数字exampleNumber。我将如何做到这一点?

谢谢

【问题讨论】:

    标签: lua lua-api


    【解决方案1】:

    只需在模块表中输入一个数字即可。

    #include <lua.h>
    #include <lauxlib.h>
    
    static char const VERSION[] = "0.1.0";
    
    // Method implementation
    static int example(lua_State* L){
        return 0;
    }
    
    // Register library using this array
    static const luaL_Reg examplelib[] = {
        {"example", example},
        {NULL, NULL}
    };
    
    // Piece it all together
    LUAMOD_API int luaopen_libexample(lua_State* L){
        luaL_newlib(L, examplelib);
    
        // Set a number in the module table
        lua_pushnumber(L, 1729);
        lua_setfield(L, -2, "exampleNumber");
    
        // Set global version string
        lua_pushstring(L, VERSION);
        lua_setglobal(L, "_EXAMPLE_VERSION");
    
        return 1;
    }
    

    然后编译

    gcc -I/usr/include/lua5.2 -shared -fPIC -o libexample.so test.c -llua5.2
    

    并像使用它

    local ex = require"libexample"
    print(ex.exampleNumber)
    

    【讨论】:

    • 谢谢!你能解释一下为什么我在 lua_setfield 中需要 -2 吗? Lua 手册对于 API 初学者来说有点混乱
    • @AlgoRythm luaL_newlib 为模块创建一个表并将其推入堆栈。那时它的索引是-1。然后将数字 1729 压入堆栈,堆栈的索引为 -1,并将模块表下压至 -2。函数lua_setfield 弹出堆栈的最高值(-1)并将其放入位于第二个参数指定的索引处的表中,名称在第三个参数中。
    猜你喜欢
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2014-02-15
    相关资源
    最近更新 更多