pub struct WeakValue { /* private fields */ }
Expand description
A weak reference to some datum or atom in the game.
Normal Value
s are not safe to move between threads.
Using methods like Value::set
or Value::call
can at best cause undefined behavior,
at worst crash the server.
A way to bypass that limitation is to store a raw value
and use Value::from_raw
on the main thread to actually work
with it. However, if that Value
is deleted, your stored value
will point to another datum or to simply nothing.
This struct serves to solve the latter problem. You can use
Value::as_weak
to create a weak reference to it.
The reference can be stored in global structures or passed to
other threads. You can then return it to the main thread as needed,
and call WeakValue::upgrade
to turn it back into a real Value
.
If the datum pointed to was deleted in the meantime, upgrade
will
return None, otherwise you get your datum back.
However, this struct is not entirely thread safe, since you can
WeakValue::upgrade
on another thread and invoke undefined behavior with
the resulting Value
. So, don’t do that.
Using this struct requires all datums to have a __auxtools_weakref_id
variable.
Example
let weakref = thing.as_weak()?;
callbacks.set(some_id, weakref);
... some proc calls later ...
let weakref = callbacks.get(some_id);
if let Some(thing) = weakref.upgrade() {
thing.call("callback", &[])?;
}
Implementations§
source§impl WeakValue
impl WeakValue
sourcepub fn upgrade(&self) -> Option<Value>
pub fn upgrade(&self) -> Option<Value>
Converts the stored raw value to a full fledged Value
and checks if it has been deleted in the meantime.
sourcepub fn upgrade_or_null(&self) -> Value
pub fn upgrade_or_null(&self) -> Value
Same as WeakValue::upgrade
but returns a null if the datum was deleted,
so you can pass it straight into DM.