让我们创建一个使用全局 int
的简单C模块5.3 :
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
。我还在做什么错?
c关闭的up值未共享,只有lua关闭的up值。每个C关闭都直接包含其高价(请参见此处)。如果您想对两个或多个C关闭两个或多个C的共享值,请使用一个公共表作为所有共享表作为upvalue,并将您的共享值放入其中,或者将注册表用于您的共享数据。
类似以下内容应该做您想要的事情:
#include <lua.h>
#include <lauxlib.h>
/* getint and setint may only be called from Lua C functions that
* have the shared table as upvalue 1.
*/
static int getint(lua_State *L){
int v = 0;
lua_getfield(L, lua_upvalueindex(1), "myint");
v = lua_tointeger(L, -1);
lua_pop(L, 1); /* remove integer from stack */
return v;
}
static void setint(lua_State *L, int v){
lua_pushinteger(L, v);
lua_setfield(L, lua_upvalueindex(1), "myint");
}
static int l_test(lua_State *L){
int Global = getint(L);
Global++;
setint(L, Global);
lua_pushinteger(L, Global);
return 1;
}
static int l_anotherTest(lua_State *L){
int Global = getint(L);
Global++;
Global++;
setint(L, Global);
lua_pushinteger(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_newtable(L);
lua_pushinteger(L, 1);
lua_setfield(L, -2, "myint");
luaL_setfuncs(L, testLib, 1);
return 1;
}