简体   繁体   中英

Lua “attempt to index a nil value”

I'm trying to register a vector type with Lua, but I'm getting a strange "attempt to index a new value" error when I'm calling the addition metafunction from Lua.

Here is the code section involved. I did not include any other metafunctions (they have the same problem, the only difference is the math operator used in one of the last lines). The error seems to come from the static int LuaVector_lua___add(lua_State *L) function.

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");
}

It crashes with the code:

local vec1 = Vector.new(2, 2)
local vec2 = Vector.new(4, 4)
local vec3 = vec1 + vec2

I tried to isolate what caused it, but I couldn't determine the actual line that is faulty (though, I believe it's lua_gettable that triggers the error itself). So it could be anything, but I can't seem to figure it out.

lua_pop Pops n elements from the stack

But you have written lua_pop(L, -1) (which clears the entire stack). Change these to lua_pop(L, 1) to pop just the top of the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM