lua-users home
lua-l archive

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

On 12.11.21 15:32, Andrew Gierth wrote:
> 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

Thank you for pointing this out. I never recognised that there are differences
regarding memory errors in lua_pushcfunction between the Lua versions...

So besides using luaL_ref another solution that also works for Lua 5.1 could be
to push the C function before the other memory allocation:

luaL_checkstack(L, 5, NULL); // assures enough space on the stack
lua_pushcfunction(L, &auxpushstr);
int auxFunc = lua_gettop(L);

char *p = returns_some_allocated_thing();
if (!p) {
     lua_pushstring("out of memory");
     return lua_error(L);
int status = ppushstring(L, auxFunc, p);  // uses only stack slots
if (status != LUA_OK) {
     return lua_error(L);
return 1;

/* protected push string */
static int ppushstring (lua_State *L, int auxFunc, const char *s) {
   int status;
   lua_pushvalue(L, auxFunc);
   lua_pushlightuserdata(L, s);
   status = pcall(L, 1, 1, 0);
   return status;

Best regards,