[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: Andrew Gierth <andrew@...>
- Date: Fri, 12 Nov 2021 15:16:09 +0000
>>>>> "ellie" == ellie <el@horse64.org> writes:
ellie> Hi everyone,
ellie> I am currently scratching my head on how to solve this best:
ellie> char *p = returns_some_allocated_thing();
ellie> if (!p) {
ellie> lua_pushstring("out of memory");
ellie> return lua_error(l);
ellie> }
ellie> lua_pushstring(l, p); // if this has an OOM error, p leaks!
ellie> free(p);
ellie> return 1;
Besides the approach already discussed, another solution to this is
to use the GC to clean up any leaks. With suitable helper functions
you could do something like:
char **p = push_string_helper(L);
*p = returns_some_allocated_thing();
if (!*p)
return luaL_error(L, "whatever");
replace_string_helper(L, -1);
return 1;
The idea is that push_string_helper would push a full userdata object
holding a pointer, with a __gc metamethod that does a free() on the
pointer if it is not null. Then the replace function would push the
string, null out the pointer, and replace the userdata object on the
stack with the new string.
(This is essentially your idea of having a global clean-up list, except
that it's using the existing lua GC to do all the work for you)
--
Andrew.