如何在Lua中删除表? [英] How to delete a table in Lua?

查看:596
本文介绍了如何在Lua中删除表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看以下代码.

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

    a:doSth()

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

我发现此方法无效.表a仍然存在.为什么? 我知道a = nil可以回收表a所拥有的内存.

I found that this method doesn't work. The table a still exists. Why? I know the a = nil can reclaim the memory which table a holds. How to directly get the memory holds by the table a and free the memory just like delete in C++?

推荐答案

function a:doSth()
    self = nil
end

是语法糖

function a.doSth(self)
    self = nil
end

您的上述代码对函数表中的值{1,2,3}有两个不同的引用,一个是通过local a,另一个是通过self. nil删除其中一个引用不会更改该表的另一个引用.

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. niling out one of the references doesn't change the other reference to the table.

要将该表考虑用于gc收集,必须确保没有引用指向该表.例如:

For that table to be considered for gc collection, you have to make sure no references point to it. For example:

function a:doSth()
    a = nil
end

这将释放a的引用,仍然有self的引用,但是当函数结束时,它会自动超出范围.调用函数后,假设没有其他引用该表,{1,2,3}将在下一个周期由gc收集.

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. After the function call, {1,2,3} will get collected by the gc on the next cycle assuming nothing else refers to that table.

这篇关于如何在Lua中删除表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆