lua-users home
lua-l archive

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


> I am currently scratching my head on how to solve this best:
> 
> char *p = returns_some_allocated_thing();
> if (!p) {
>     lua_pushstring("out of memory");
>     return lua_error(l);
> }
> lua_pushstring(l, p);  // if this has an OOM error, p leaks!
> free(p);
> return 1;

One way to solve this is to do the lua_pushstring inside a pcall. You
can pass 'p' as a light userdata in the pcall. Something roughly like
this:

static int auxpushstr (lua_State *L) {
  char *p = (char *)lua_touserdata(L, 1);
  lua_pushstring(L, p);
  return 1;
}

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


-- Roberto