LUAAPI-向新库添加编号

LUAAPI-向新库添加编号,lua,lua-api,Lua,Lua Api,(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",

(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
。我将如何做到这一点


谢谢

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

#包括
#包括
静态字符常量版本[]=“0.1.0”;
//方法实现
静态int示例(lua_State*L){
返回0;
}
//使用此数组注册库
静态常量luaL_Reg examplelib[]={
{“示例”,示例},
{NULL,NULL}
};
//拼凑
LUAMOD_API int luaopen_libexample(lua_State*L){
luaL_newlib(L,examplelib);
//在模块表中设置一个数字
卢奥·普什号码(L,1729);
lua_设置域(L,-2,“示例编号”);
//设置全局版本字符串
lua_推力串(L型);
lua_setglobal(L,“_示例_版本”);
返回1;
}
然后用

gcc-I/usr/include/lua5.2-shared-fPIC-o libexample.so test.c-llua5.2
像这样使用它

localex=需要“libexample”
打印(例如,示例编号)

谢谢!你能解释一下为什么我在lua_setfield中需要-2吗?对于初学者来说,Lua手册有点让人困惑API@AlgoRythm
luaL_newlib
为模块创建一个表并将其推送到堆栈上。在这一点上,它的指数是-1。然后将数字1729推到堆栈上,该堆栈的索引为-1,并将模块表向下推到-2。函数
lua_setfield
弹出堆栈的最高位值(-1),并将其放入位于第二个参数指定的索引处的表中,第三个参数的名称为。