kFk
kFk

Reputation: 409

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.

Upvotes: 3

Views: 2796

Answers (2)

kikito
kikito

Reputation: 52648

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

Upvotes: 5

Bryan McLemore
Bryan McLemore

Reputation: 6493

I'm not certain about integrating it with C++ but it sounds like the garbage collector isn't being given an opportunity to run.

In your lua you could try explicitly invoking it and see if that helps. There is a function in the core apis collectgarbage(opt [, arg]).

Upvotes: 1

Related Questions