Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lost references in Lua

Having a problem with objects, not needed any more but still having references. Result: size of allocated memory is constantly growing due to not collected objects.

How to solve this sort of problem? Is there any way to find objects with only one reference, or objects with lifetime more than some value? Or any another solution?

Using Lua 5.1 and C++ with luabind.

Thanks.

like image 548
kFk Avatar asked Feb 11 '26 08:02

kFk


1 Answers

As someone is mentioning here, you can try using weak tables.

If you have some code like this:

myListOfObjects = {}
...
table.insert(myListOfObject, anObject)

Then once anObject stops being used, it will never be deallocated since myListOfObjects still references it.

You could try removing the reference in myListOfObjects (setting the reference to nil) but a simpler solution is declaring myListOfObjects as a weak table:

myListOfObjects = {}
setmetatable(myListOfObjects, { __mode = 'v' }) --myListOfObjects is now weak

Given that setmetatable returns a reference to the table it modifies, you can use this shorter idiom, which does the same as previous two lines:

myListOfObjects = setmetatable({}, {__mode = 'v' }) --creation of a weak table
like image 129
kikito Avatar answered Feb 15 '26 13:02

kikito