What am I allowed to do with the Lua stack and its contents in my C functions?

The stack you get in your C function was created especially for that function and you can do with it whatever you want. So feel free to remove function arguments that you don't need anymore. However, there is one scenario to watch out for: never remove a Lua string from the stack while you still have a pointer to the C string inside it (obtained with lua_tostring):

/* assume the stack contains one string argument */
const char* name = lua_tostring(L, 1);
lua_pop(L, 1); /* careful... */
puts(name); /* bad! */

If you remove the Lua string from the stack there's a chance that you removed the last reference to it and the garbage collector will free it at the next opportunity, which leaves you with a dangling pointer.



Back