pub struct StatefulCommand<T> { /* private fields */ }Expand description
A wrapper for creating stateful commands.
The StatefulCommand type enables the creation of Tcl commands that are
stateful. In other words, they can be modified and carry-forward their
state to future invocations (in contrast to the create_command method
of Interpreter where the function must either be pure (from Tcl’s
perspective) or use global state).
§Example
use std::cell::RefCell;
use rtea::*;
fn create_stateful_command(interp: &Interpreter) {
fn cmd(
interp: &Interpreter,
counter: &RefCell<usize>,
_args: Vec<&str>,
) -> Result<TclStatus, String> {
let mut val = counter.borrow_mut();
interp.set_result(&val.to_string());
*val += 1;
Ok(TclStatus::Ok)
}
let c = StatefulCommand::new(cmd, RefCell::<usize>::new(0));
c.attach_command(interp, "counter").unwrap();
for i in 0..10 {
interp.eval("counter").unwrap();
assert_eq!(i.to_string(), interp.get_obj_result().get_string());
}
}Implementations§
Source§impl<T> StatefulCommand<T>
impl<T> StatefulCommand<T>
Sourcepub fn new(
proc: fn(interp: &Interpreter, data: &T, args: Vec<&str>) -> Result<TclStatus, String>,
data: T,
) -> StatefulCommand<T>
pub fn new( proc: fn(interp: &Interpreter, data: &T, args: Vec<&str>) -> Result<TclStatus, String>, data: T, ) -> StatefulCommand<T>
Creates a new StatefulCommand.
The creates a new StatefulComand with ownership of data. The
underlying implementation should be as thread-safe as the original
implementation of data, but care needs to be taken to ensure that
any concurrency from Tcl is safe on data (there are no concerns for
proc).
Sourcepub fn attach_command(
self,
interp: &Interpreter,
name: &str,
) -> Result<TclStatus, String>
pub fn attach_command( self, interp: &Interpreter, name: &str, ) -> Result<TclStatus, String>
Attaches the StatefulCommand to a Tcl interpreter.
This exposes the instantiated StatefulCommand to the given
interpreter. This should allow exposing a command to multiple
interpreters (or as aliases in the same interpreter) for advanced
functionality. While the borrow checker should prevent some misuses
(type is passed by ownership), this has not been heavily tested for
every type T.