On Wed, Aug 31, 2011 at 9:22 AM, Robert Raschke
<rtrlists@googlemail.com> wrote:
On Wed, Aug 31, 2011 at 2:15 PM, oliver
<oliver.schoenborn@gmail.com> wrote:
Checkstack is only useful when you push stuff onto the stack. But how do you validate, say, an index you give to a C function that queries the Lua stack? For instance:
int someFunc(int stackIndex) {
return lua_tonumber(L, stackIndex);
}
The lua_tonumber does not check that index is acceptable; if it is not, it can return garbage (0, NaN, whatever) and the caller wouldn't know that app state is now undefined.
The only solution is to assert that stackIndex != 0 and abs(stackIndex) <= top, or?
Oliver
...
Here, lua_gettop() may be used to check that you do in fact have at least as many elements on the top as you expect.
Robby
Which is the formula I gave above (stackIndex != 0 and abs(stackIndex) <= top).
But this is more restrictive than necessary. For instance, take lua_type, which another poster suggested: "Returns the type of the value in the given acceptable index, or LUA_TNONE for a non-valid index (that is, an index to an "empty" stack position)." Non-valid here refers to an index which satisfies lua_gettop() < index < stackspace, not an index that is outside of the stack bounds (1..20 or such). But since there is no official way of knowing stack space (again, you can't assume the default of 20), you can never check this and so should never call lua_type (or any other Lua C API function) with an index > lua_gettop() because if it is > lua_gettop(), it could also be > stackspace. Your own code will have to check > lua_gettop(), and return LUA_TNONE, rather than relying on lua_type to do so. This has bitten many programmers.
Oliver