Skip to main content

with_instance

Function with_instance 

Source
pub fn with_instance<T, R>(f: impl FnOnce(&mut T) -> R) -> Option<R>
where T: SampPlugin + 'static,
Expand description

Runs f with the plugin instance, on the main thread.

This is the general way to reach plugin state from code the plugin does not own the call site of — a main-thread job, a callback helper, a timer — where there is no &mut self in scope.

let sent = samp::plugin::with_instance::<MyPlugin, _>(|plugin| {
    plugin.sent += 1;
    plugin.sent
});

Returns None, having logged why, when the plugin cannot be lent out:

  • T is not the type the plugin was created as;
  • the plugin does not exist yet, or no longer does;
  • a borrow is already alive — a nested with_instance, or a call from inside a native, which already holds &mut self. Use that self.

Must be called from the main thread. There is nothing to synchronize with off it: the plugin is not Sync, and the server touches it from one thread. Work arriving on another thread belongs in crate::mainthread::post_with, which calls through here at the right moment.