表、嵌套表的 Lua 垃圾回收
[我已经阅读了 Lua 手册,但它没有提供可靠的答案。]
假设我有一个 Lua 表,充当索引数组:
local myArray = {};
myArray[1] = "Foo";
myArray[2] = "Bar";
我如何最好地处理这个表? 我只是将 myArray 设置为 nil 吗? 或者我是否必须迭代数组并将每个索引元素设置为零?
同样,假设我有一个 Lua 表,充当字典:
local myDictionary = {};
myDictionary["key1"] = "Foo";
myDictionary["key2"] = "Bar";
我可以将 'myDictionary' 设置为 nil,还是必须迭代?
最后,在内存管理方面,我在嵌套表的地方该怎么做? 例如,
local myNestedCollection = {};
myNestedCollection[1] = {1, 2, 3};
myNestedCollection[2] = {4, 5, 6};
我是否需要遍历每个子表,将它们设置为零? 谢谢你的帮助。
[I've read the Lua manual, but it did not provide solid answers.]
Let's say I have a Lua Table, acting as an indexed array:
local myArray = {};
myArray[1] = "Foo";
myArray[2] = "Bar";
How do I best dispose of this Table? Do I just set myArray to nil? Or do I have to iterate through array and set each indexed element to nil?
Similarly, let's say I have I have a Lua Table, acting as a dictionary:
local myDictionary = {};
myDictionary["key1"] = "Foo";
myDictionary["key2"] = "Bar";
Can I just set 'myDictionary' to nil, or do I have to iterate through?
Lastly, what do I do, memory-management wise, where I have nested Tables? e.g.
local myNestedCollection = {};
myNestedCollection[1] = {1, 2, 3};
myNestedCollection[2] = {4, 5, 6};
Do I need to iterate through each of these sub-tables, setting them to nil? Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将局部变量设置为 nil 就足够了; 无需遍历所有键并将它们设置为 nil 。 根据本页,Lua使用标记和清除垃圾收集算法。 一旦将局部变量设置为
nil
,其表中的键就变得不可访问,因此它们将在下一次收集时被垃圾收集器收集。 同样,如果这些对象也是表,它们的键也将变得无法访问,因此它们也将被收集。It should be sufficient just to set the local variable to
nil
; there's no need to iterate through all of the keys and set them tonil
to. According to this page, Lua uses a mark-and-sweep garbage collection algorithm. As soon as you set your local variable tonil
, the keys in its table become unreachable, so they will be collected by the garbage collector on the next collection. Similarly, if those objects are also tables, their keys will also become unreachable, so they too will be collected.在大多数 GC 中,当没有对某个对象的引用时,该对象就会被收集。 将引用链的顶部设置为零会删除对子级的引用。 如果这是唯一的参考,那么孩子们将被收集。
In most GC an object will be collected when there are no references to it. Setting the top of your reference chain to nil removes a reference to the children. If that was the only reference then the children will be collected.