lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello, everyone, list!

The manual states I am responsible for controlling the stack size. It is guaranteed that at least LUA_MINSTACK elements are available for usage without size check after the call from Lua to C. However, if you are uncertain how many free elements are already used (you are in the middle of a recursive call), you should explicitly call lua_checkstack() (or luaL_checkstack(), depending on your case). For instance, a call to lua_next(L, x) should be preceded with the call to lua_checkstack(L, 2) ensuring that at least two unused elements are available since lua_next() will pop one and push two elements in the worst case.

The problem comes with implicit stack usage by calls like luaL_ref() (and others I presume). The manual states nothing about stack usage by a call to luaL_ref(). More clearly, it states +0 usage of the stack which is false in the sense of implicit stack usage. Investigating into the source code of luaL_ref() reveals the usage of one extra stack element. The piece of code demonstrates the issue:

lua_checkstack(L, 3); // here we need to check for 3 elements available (not  2 !!!) because luaL_ref() uses one extra element implicitly
lua_newtable(L); // push a new table
lua_pushboolean(L, 1); // push some value
int r = luaL_ref(L, -2); // make reference in the table at index -2

I am totally comfortable with checking the stack gap. However, it should be explicitly documented how much stack size I need prior to making library calls which use the stack implicitly. Otherwise, it may lead to very rare and subtle error cases.

Any comments?

// Seny