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