What are weak references?

Viewed 214

I tried to understand weak tables/weak references but still can't understand anything.

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

I found this in Programming in Lua First Edition, but the next thing it said really confused me

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

Also this information(not from the book though)

"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

The object is only held inside a weak table(which is t), but Lua doesn't collect this. I still can print the table, the table isn't got rid by the garbage collector.

This information also got proved by 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."

Is there anything wrong with the information I gathered or the code I showed? I'm pretty bad at learning things, thus I have to ask many questions. If yes then please give me right the right information and some specific examples.

EDIT: I understood how does weak tables and weak references work now, also I learnt a new thing about table.insert() : I can insert tables with table.insert(), seems amazing.

1 Answers

First off, you have to declare the table as weak (that is, having either weak keys or weak values or both)

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

Then you can store an object in the table

table.insert(weak, {"hello", "world"})

Since there is no other reference to the object except as a value in the table, it will get collected by the GC the next time it runs. The entire key-value-pair will then be gone from the table and it will be empty, as there were no other paris.

Related