[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Lua userdata and garbage collection
- From: Andreas Falkenhahn <andreas@...>
- Date: Sat, 25 Nov 2023 15:22:30 +0100
I'm working on a Lua binding for a C library where each object allocated by the C library is stored as a Lua userdata object with a metatable that handles method calls for the object and also adds a __gc function for the garbage collector so that the C object is deleted as soon as there are no more references to it in the Lua script. This basically works but I'm wondering what the best way to solve the problem of garbage collection is in this case?
For example, consider the situation where the C library is used to allocate a list and list items. The C code looks something like this:
static int alloclist(lua_State *L)
{
struct mylist *p = lua_newuserdata(L, sizeof(mylist));
setmetatable(...);
p->obj = alloc_the_list();
return 1;
}
static int alloclistitem(lua_State *L)
{
struct mylistitem *p = lua_newuserdata(L, sizeof(mylistitem));
setmetatable(...);
p->obj = alloc_the_list_item();
return 1;
}
Now imagine the following situation in a Lua script:
local list = alloclist()
local listitem = alloclistitem()
list:insertitem(listitem)
listitem = nil
Now "listitem" is marked for garbage collection even though it is still referenced by "list" because it has been inserted into the list using "list:insertitem()".
The only way I see to solve this is to not use userdata at all but allocate custom memory for each object and implement a separate free() method that has to be explicitly called when the script is done with an object. Or is there a better way to do this?
--
Best regards,
Andreas Falkenhahn mailto:andreas@falkenhahn.com