pub trait CustomType: Variant + Clone {
// Required method
fn build(builder: TypeBuilder<'_, Self>);
}
Expand description
Trait to build the API of a custom type for use with an Engine
(i.e. register the type and its getters, setters, methods, etc.).
§Example
use rhai::{CustomType, TypeBuilder, Engine};
#[derive(Debug, Clone, Eq, PartialEq)]
struct TestStruct {
field: i64
}
impl TestStruct {
fn new() -> Self {
Self { field: 1 }
}
fn update(&mut self, offset: i64) {
self.field += offset;
}
fn get_value(&mut self) -> i64 {
self.field
}
fn set_value(&mut self, value: i64) {
self.field = value;
}
}
impl CustomType for TestStruct {
fn build(mut builder: TypeBuilder<Self>) {
builder
// Register pretty-print name of the type
.with_name("TestStruct")
// Register display functions
.on_print(|v| format!("TestStruct({})", v.field))
.on_debug(|v| format!("{v:?}"))
// Register a constructor function
.with_fn("new_ts", Self::new)
// Register the 'update' method
.with_fn("update", Self::update)
// Register the 'value' property
.with_get_set("value", Self::get_value, Self::set_value);
}
}
let mut engine = Engine::new();
// Register API for the custom type.
engine.build_type::<TestStruct>();
assert_eq!(
engine.eval::<TestStruct>("let x = new_ts(); x.update(41); print(x); x")?,
TestStruct { field: 42 }
);
Required Methods§
Sourcefn build(builder: TypeBuilder<'_, Self>)
fn build(builder: TypeBuilder<'_, Self>)
Builds the custom type for use with the Engine
.
Methods, property getters/setters, indexers etc. should be registered in this function.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.