lua-users home
lua-l archive

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


>>>>> "Meir" == Meir Shpilraien <meir@redis.com> writes:

 Meir> Hey,
 Meir> I was wondering whether or not it's OK to pop out from the stack
 Meir> the arguments given to a native C function from Lua code.

You can pop whatever you like from the current stack frame as long as
you understand that it could be garbage-collected at any time, so don't
pop anything that you are holding a C pointer to (e.g. strings or udata).

In general you shouldn't worry about this. You're guaranteed 20 free
slots above whatever arguments were passed in, and you should use
lua_checkstack or luaL_checkstack to reserve more if you need them, and
otherwise if the user passes in enough args to reach the overall stack
limit (which is NOT the LUA_MAXCSTACK one, that one limits the maximum
depth of C calls) then the resulting error is their problem. Remember
that if the user wants to overflow the stack they can always use a Lua
function to consume most of the space before calling your function.

If for some reason you need to be extra careful, it's quite OK to do a
lua_settop to discard everything beyond the number of arguments you
actually expected, as long as you don't subsequently need to check
whether those arguments were actually missing rather than supplied as
nil. For example, if a C function "foo" does lua_settop(L,3); at start,
then it can no longer distinguish whether it was called as foo(1,2,nil)
or foo(1,2). This distinction usually doesn't matter; in fact this is
often done in order to be able to safely refer to optional arguments by
stack index.

 Meir> I am using Lua 5.1.5 (if it makes any difference).

One difference between 5.1 and later Lua versions (which you should
upgrade to, unless you're committed to luajit or to an environment which
embeds 5.1 and can't be updated) is that 5.1 lacks any good way to
handle memory errors from lua_checkstack. In 5.2 onwards, lua_checkstack
will return an error rather than throwing an error if memory is
exhausted when allocating new stack space.

-- 
Andrew.