lua-users home
lua-l archive

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


On Tue, Jul 28, 2009 at 1:50 AM, Mark Hamburg wrote:
> I like the light userdata holding the C function pointer trick. Of course,
> we still need a way to push without throwing or at least to guarantee the
> existence of stack space without throwing.

We have at least LUA_MINSTACK positions available.
lua_pushlightuserdata and many of the other lua_push* functions are
guaranteed not to fail if stack space is available.  The few that can
fail (e.g. lua_pushstring) due to memory allocation can be wrapped in
a pcall that returns the constructed object on the stack.  Stack space
usage can be determined by static code analysis.

If we need more than LUA_MINSTACK, then we can call lua_checkstack.
However, lua_checkstack can longjump.  We cannot just wrap
lua_checkstack alone in a pcall since pcall runs under a different
stack space.  We'd normally be advised to refactor our code so that
the lua_checkstack and whatever other operations we'd want to perform
are both inside that pcall.  However, I can think of a workaround to
avoid refactoring: lua_pcall an empty function with nresults set to
the number of stack spaces you want to add and then pop the nil's from
the stack.  This has the same effect as lua_checkstack but will never
longjump.

A much better solution would be for Lua to provide a version
lua_checkstack that doesn't longjump.  Preventing longjumps is a
recurring problem of mine that pushes toward refactoring code in a way
I don't want or going through contortions.