让我们创建一个简单的C模块的Lua 5.3与全球int
:Lua中共享使用C
static int l_test(lua_State *L){
int Global = lua_tointeger(L, lua_upvalueindex(1));
Global++;
lua_pushinteger(L, Global);
lua_pushvalue(L, -1);
lua_replace(L, lua_upvalueindex(1));
//lua_pushnumber(L, Global);
return 1;
}
static int l_anotherTest(lua_State *L){
int Global = lua_tointeger(L, lua_upvalueindex(1));
Global++;
Global++;
lua_pushinteger(L, Global);
lua_pushvalue(L, -1);
lua_replace(L, lua_upvalueindex(1));
//lua_pushnumber(L, Global);
return 1;
}
static const struct luaL_Reg testLib [] = {
{"test", l_test},
{"anotherTest", l_anotherTest},
{NULL, NULL}
};
int luaopen_testLib(lua_State *L){
luaL_newlibtable(L, testLib);
lua_pushinteger(L, 1);
luaL_setfuncs(L, testLib, 1) ;
return 1;
}
这几乎是工作,但是当我调用这两个函数从Lua是这样的:
local testLib = require "testLib"
print(testLib.test())
print(testLib.anotherTest())
第二次打印应该是4
,但它会打印出3
。 我还在做什么错?
要调用刚刚'setfuncs'之前初始化的upvalue,你应该推动其初始值压入堆栈。要从'l_test'访问upvalue,你应该使用'lua_upvalueindex(1)'来获得这个值所在的栈pseudoindex。 –
感谢您的提示。我已经更新了这个问题。这里仍然缺少一些东西。你可以帮我吗? – user1511417
如果您想要一个空指针常量,则使用'NULL'宏。使用整数'0'是一个令人迷惑的遗产。 – Olaf