lua-users home
lua-l archive

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

>>>>> "ellie" == ellie  <> writes:

 ellie> Thanks for the response, that was quick!

 ellie> I'm wondering though, couldn't the lua_pushcfunction itself
 ellie> cause an out of memory error too?

Depends on the lua version.

In 5.1 (and therefore luajit), lua_pushcfunction can throw error for out
of memory, for which a possible workaround is to previously stash a copy
of the function object in the registry with luaL_ref and use lua_rawgeti
to fetch it (lua_rawgeti cannot throw errors). In some cases lua_cpcall
could be used instead, but it doesn't allow returning values, so it's
not useful here.

In 5.2 onward, there are two 5.3.x releases (5.3.3 and .4, iirc) in
which lua_pushcfunction can throw errors (due to incorrectly invoking
the GC, so errors propagating from a __gc metamethod can escape), but
that's a bug that was fixed. Unfortunately there's no way to check the
minor version at run time, as far as I know.

Remember that the stack itself always has to be preallocated (either
because you didn't yet use up the 20 free slots you get at function
entry, or because you used lua_checkstack or luaL_checkstack to ensure
space was available). This is why pushing already-allocated values (e.g.
results from a rawget on the registry) or non-allocatable values like
integers, light userdata, and (in 5.2+, barring bugs) light C functions
doesn't risk throwing an error.

There are still various annoying defects in the API in this area though.
One of them is that there's no interface provided to push the "not
enough memory" string safely; while lua_pushstring won't actually throw
an error when pushing it, since it's a pre-allocated interned short
string, that relies on the application knowing the exact value to push.