什么是弱引用?

What are weak references?

我试图理解较弱的 tables/weak 引用,但仍然无法理解任何内容。

"A weak reference is a reference to an object that is not considered by the garbage collector"

我在 Programming in Lua First Edition 中找到了这个,但接下来它说的让我很困惑

"That means that, if an object is only held inside weak tables, Lua will collect the object eventually."

还有这个信息(虽然不是来自书本)

"An object is considered as "garbage" if it has 0 references"

local t = {x = val} -- x is a weak reference because val isn't considered as "garbage" even after getting removed, x is still a reference of val

val = nil

collectgarbage() --you'd expect {} to be collected

for i, v in pairs(t) do
    print(v) --prints the table
end

该对象仅保存在弱 table(即 t)中,但 Lua 不收集此对象。我仍然可以打印 table,table 没有被垃圾收集器清除。

这个信息也被Lua 5.1 Reference Manual

证实了

"In other words, if the only references to an object are weak references, then the garbage collector will collect this object."

我收集的信息或我显示的代码有什么问题吗?我学东西很差,所以我不得不问很多问题。 如果是,请给我正确的信息和一些具体的例子。

编辑:我了解了弱 table 和弱引用现在是如何工作的,我还学到了关于 table.insert() 的新知识:我可以用 table.insert() 插入 tables,看起来很神奇。

首先,您必须将 table 声明为弱(即具有弱键或弱值或两者)

local weak = setmetatable({}, {__mode="v"}) -- Create table weak with weak values

然后你可以在table

中存储一个对象
table.insert(weak, {"hello", "world"})

由于除了 table 中的值外,没有对该对象的其他引用,它将在下次运行时被 GC 收集。然后整个键值对将从 table 中消失,它将是空的,因为没有其他 paris。