Quirrel4.41.0

types.WeakRef.ref

Method on every weakref
weakref.ref(): any

Returns the value this weakref points at, or null once that value is gone.

examples/types/weakref/ref-basic.nut
let crate = { ammo = 10 }
let wr = crate.weakref()
println("wr.ref() == crate =", wr.ref() == crate)   // crate is still alive, so ref() hands it back
Output:
wr.ref() == crate = true

Return value

The original value for as long as something else still holds a strong reference to it. Once the last strong reference is dropped, ref() returns null instead - it never throws for a dead reference.

Notes

Takes no arguments; wr.ref(1) throws a wrong-number-of-parameters error.

Dropping a variable's value does not always show up immediately: leaving a { } block does not, by itself, release a local's reference the moment control leaves the block - the value's slot on the VM stack keeps holding it until something later overwrites that same slot. Setting the variable to null explicitly forces the release at a known point; relying on scope exit alone for a "did it die yet" check is not reliable.

A weakref to a value that was never reference counted in the first place (an integer, float, bool or null) never goes dead, because ref() returns that same value every time - see types.WeakRef.constructor.

Example

examples/types/weakref/ref.nut
local t = {a = 1}
let wr = t.weakref()

// Dropping the only strong reference lets ref() see the table is gone.
t = null
println("wr.ref() =", wr.ref())
Output:
wr.ref() = null

See also

constructorReturns a weak reference to obj. This is what runs when types.WeakRef itself is called, types.WeakRef(obj) - the same conversion obj.weakref() performs as a method.
weakrefReturns a weak reference to this weakref.
weakrefReturns a weak reference to the table.
weakrefclass index