开发者

Lost references in Lua

开发者 https://www.devze.com 2022-12-14 11:54 出处:网络
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.

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开发者_StackOverflow中文版 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.


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


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]).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号