[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Is there something like a lua_trypushstring() with return value? Could there be?
- From: Roberto Ierusalimschy <roberto@...>
- Date: Fri, 12 Nov 2021 10:21:56 -0300
> 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