简体   繁体   English

如何删除Lua中的表?

[英]How to delete a table in Lua?

Let us see the following codes. 让我们看看以下代码。

do
    local a = {1,2,3}
    function a:doSth()
        self = nil
    end

    a:doSth()

    if a then
        print("Still has a...")
    end
end

I found that this method doesn't work. 我发现这种方法不起作用。 The table a still exists. a仍然存在。 Why? 为什么? I know the a = nil can reclaim the memory which table a holds. 我知道a = nil可以回收表a拥有的内存。 How to directly get the memory holds by the table a and free the memory just like delete in C++? 如何直接获取表a的内存并释放内存就像在C ++中delete一样?

function a:doSth()
    self = nil
end

Is syntax sugar for 是语法糖

function a.doSth(self)
    self = nil
end

Your above code, there are two different references to the table value {1,2,3} , one is through local a , the other is through self inside the function. 你的上面的代码,有两个不同的引用值{1,2,3} ,一个是通过local a ,另一个是通过self里面的函数。 nil ing out one of the references doesn't change the other reference to the table. nil out out其中一个引用不会更改对表的其他引用。

For that table to be considered for gc collection, you have to make sure no references point to it. 要将该表考虑用于gc集合,您必须确保没有引用指向它。 For example: 例如:

function a:doSth()
    a = nil
end

That will release the reference by a , there is still a reference from self but that automatically goes out of scope when the function ends. 这将通过a释放引用,仍然有来自self的引用,但是当函数结束时自动超出范围。 After the function call, {1,2,3} will get collected by the gc on the next cycle assuming nothing else refers to that table. 在函数调用之后,假设没有其他任何内容引用该表,gc将在下一个周期收集{1,2,3}

You can do this: 你可以这样做:

a = nil
collectgarbage()

However I don't recommend running a full garbage collection cycle just to liberate 1 table. 但是我不建议运行完整的垃圾收集周期只是为了解放1个表。 Garbage collection takes time and it is better to leave Lua to run it when it sees fit. 垃圾收集需要时间,最好让Lua在它认为合适时运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM