0
我试图向Lua注册一个向量类型,但是当我从Lua调用附加元函数时,出现了一个奇怪的“尝试索引新值”错误。Lua“试图索引一个零值”
这是涉及的代码部分。我没有包含任何其他的元函数(他们有相同的问题,唯一的区别是最后一行中使用的数学运算符)。该错误似乎来自static int LuaVector_lua___add(lua_State *L)
函数。
static void LuaVector_pushVector(lua_State *L, double x, double y)
{
lua_newtable(L);
lua_pushstring(L, "x");
lua_pushnumber(L, x);
lua_settable(L, -3);
lua_pushstring(L, "y");
lua_pushnumber(L, y);
lua_settable(L, -3);
lua_newtable(L);
lua_pushstring(L, "__add");
lua_pushcfunction(L, LuaVector_lua___add);
lua_settable(L, -3);
lua_setmetatable(L, -2);
}
static int LuaVector_lua___add(lua_State *L)
{
if (!lua_istable(L, 1))
luaL_error(L, "Table excepted for argument #1 LuaVector_lua___add");
if (!lua_istable(L, 2))
luaL_error(L, "Table excepted for argument #2 LuaVector_lua___add");
double x1=0, y1=0, x2=0, y2=0;
/* The error occurs somewhere between here */
lua_pushstring(L, "x");
lua_gettable(L, 1);
x1 = lua_tonumber(L, -1);
lua_pop(L, -1);
lua_pushstring(L, "y");
lua_gettable(L, 1);
y1 = lua_tonumber(L, -1);
lua_pop(L, -1);
lua_pushstring(L, "x");
lua_gettable(L, 2);
x2 = lua_tonumber(L, -1);
lua_pop(L, -1);
lua_pushstring(L, "y");
lua_gettable(L, 2);
y2 = lua_tonumber(L, -1);
lua_pop(L, -1);
/* And here */
LuaVector_pushVector(L, x1 + x2, y1 + y2);
return 1;
}
int LuaVector_lua_new(lua_State *L)
{
double x = 0;
if (!lua_isnil(L, 1))
x = lua_tonumber(L, 1);
double y = 0;
if (!lua_isnil(L, 2))
y = lua_tonumber(L, 2);
LuaVector_pushVector(L, x, y);
return 1;
}
void LuaVector_luaregister(lua_State *L)
{
lua_newtable(L);
lua_pushstring(L, "new");
lua_pushcfunction(L, LuaVector_lua_new);
lua_settable(L, -3);
lua_setglobal(L, "Vector");
}
它的代码崩溃:
local vec1 = Vector.new(2, 2)
local vec2 = Vector.new(4, 4)
local vec3 = vec1 + vec2
我试图孤立什么原因造成的,但我不能确定实际的线是错误的(不过,我相信这是lua_gettable
触发错误本身)。所以它可能是任何东西,但我似乎无法弄清楚。
'lua_pushstring' +'lua_settable' = [lua_setfield](http://www.lua.org/manual/5.2/manual.html#lua_setfield)。 'lua_isnil' +'lua_tonumber' = [luaL_optnumber](http://www.lua.org/manual/5.2/manual.html#luaL_optnumber)。 'lua_newtable' +'lua_push ???'+ ... = [luaL_newlib](http://www.lua.org/manual/5.2/manual.html#luaL_newlib)。 'lua_is ???'+'luaL_error' = [luaL_check ???](http://www.lua.org/manual/5.2/manual.html#luaL_checktype)。在注册表中创建一次(与库一起)的metatable(参见[luaL_newmetatable](http://www.lua.org/manual/5.2/manual.html#luaL_newmetatable)),而不是针对所有对象。 – Youka