Is it allowed to modify stack values as long as the stack stays balanced?

Viewed 99

Everybody knows it is good programming practice to keep the stack balanced. What I'm wondering, though, is whether I'm allowed to modify stack values in a C function called from a Lua script? Consider the following code:

int myfunc(lua_State *L)
{
    int arg1 = luaL_checkinteger(L, 1);
    int arg2 = luaL_checkinteger(L, 2);

    // pop arg 2
    lua_pop(L, 1);

    // this is to be our return value
    lua_newtable(L);

    ...do complicated stuff...

    // restore second parameter but set it to nil for convenience's sake
    lua_pushnil(L);
    lua_insert(L, 2);

    // return our table
    return 1;
}

So the code above replaces the second parameter with nil. Is this allowed or do I have to restore the original value, i.e. would I have to do

lua_pushinteger(L, arg2);

instead of

lua_pushnil(L);

? Or doesn't this matter as long as myfunc returns with the stack balanced?

1 Answers

The stack values are the property of the C function being called. You can do whatever you wish with them. The only effect to the outside is the values returned by the function.

C functions called from Lua do not need to keep the stack balanced, that is, with the same contents or number of items it had on entry.

Related