Quirrel4.41.0

types.Table.weakref

Method on every table
weakref(): any

Returns a weak reference to the table.

Return value

A weakref value. Calling its ref() method gives the table back for as long as something else still holds a strong reference to it; once the table's refcount drops to zero, ref() returns null instead.

Notes

Takes no arguments. Holding a weakref never keeps the table alive by itself. Use one instead of an ordinary reference to observe an object without extending its lifetime.

Storing the weakref itself in a container slot is different from holding it in a local: reading that slot back unwraps it and returns the table (or null once the table is gone), not the weakref value.

Example

examples/types/table/weakref.nut
local t = {a=1}
let w = t.weakref()
println("typeof w =", typeof w)
println("typeof w.ref() =", typeof w.ref())     // still alive: gives the table back

// storing the weakref in a container slot auto-unwraps it on read
let holder = {}
holder.slot <- w
println("typeof holder.slot =", typeof holder.slot) // not "weakref"

t = null                    // drop the only strong reference
println("w.ref() == null:", w.ref() == null)    // the table is gone now
Output:
typeof w = weakref
typeof w.ref() = table
typeof holder.slot = table
w.ref() == null: true

See also

is_frozenReports whether this reference to the table was frozen with freeze().
cloneReturns a shallow copy of the table.
tostringReturns a string that names the type and identity of the table.
tableclass index