add RhaiCustomType trait and build_type method

This commit is contained in:
Tristan Guichaoua 2022-08-08 14:43:06 +02:00
parent 7e3a4a4c52
commit b6937fd21d
3 changed files with 70 additions and 1 deletions

67
src/api/build_type.rs Normal file
View File

@ -0,0 +1,67 @@
use crate::Engine;
/// Trait to build a custom type for use with the [`Engine`].
/// i.e. register the type, getters, setters, methods, etc...
///
/// # Example
///
/// ```
/// use rhai::{Engine, RhaiCustomType};
///
/// #[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;
/// }
/// }
///
/// impl RhaiCustomType for TestStruct {
/// fn build(engine: &mut Engine) {
/// engine
/// .register_type::<Self>()
/// .register_fn("new_ts", Self::new)
/// .register_fn("update", Self::update);
/// }
/// }
///
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
///
/// let mut engine = Engine::new();
///
/// // Register API for the custom type.
/// engine.build_type::<TestStruct>();
///
/// # #[cfg(not(feature = "no_object"))]
/// assert_eq!(
/// engine.eval::<TestStruct>("let x = new_ts(); x.update(41); x")?,
/// TestStruct { field: 42 }
/// );
/// # Ok(())
/// # }
/// ```
pub trait RhaiCustomType {
/// Builds the custom type for use with the [`Engine`].
/// i.e. register the type, getters, setters, methods, etc...
fn build(engine: &mut Engine);
}
impl Engine {
/// Build a custom type for use with the [`Engine`].
/// i.e. register the type, getters, setters, methods, etc...
///
/// See [`RhaiCustomType`].
pub fn build_type<T>(&mut self) -> &mut Self
where
T: RhaiCustomType,
{
T::build(self);
self
}
}

View File

@ -28,6 +28,8 @@ pub mod custom_syntax;
pub mod deprecated;
pub mod build_type;
#[cfg(feature = "metadata")]
pub mod definitions;

View File

@ -166,7 +166,7 @@ type ExclusiveRange = std::ops::Range<INT>;
/// An inclusive integer range.
type InclusiveRange = std::ops::RangeInclusive<INT>;
pub use api::events::VarDefInfo;
pub use api::{build_type::RhaiCustomType, events::VarDefInfo};
pub use ast::{FnAccess, AST};
pub use engine::{Engine, OP_CONTAINS, OP_EQUALS};
pub use eval::EvalContext;