types.WeakRef.ref
weakrefReturns the value this weakref points at, or null once that value is gone.
let crate = { ammo = 10 }
let wr = crate.weakref()
println("wr.ref() == crate =", wr.ref() == crate) // crate is still alive, so ref() hands it backwr.ref() == crate = trueReturn 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
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())wr.ref() = nullSee also
constructor | Returns 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. |
weakref | Returns a weak reference to this weakref. |
weakref | Returns a weak reference to the table. |
| weakref | class index |