rhai/examples/custom_types_and_methods.rs

69 lines
1.6 KiB
Rust
Raw Normal View History

2022-02-12 05:41:04 +01:00
//! An example showing how to register a Rust type and methods/getters/setters for it.
#[cfg(feature = "no_object")]
fn main() {
panic!("This example does not run under 'no_object'.");
}
use rhai::{Engine, EvalAltResult};
2022-02-10 05:54:30 +01:00
#[cfg(not(feature = "no_object"))]
fn main() -> Result<(), Box<EvalAltResult>> {
#[derive(Debug, Clone)]
struct TestStruct {
x: i64,
}
2022-02-10 05:54:30 +01:00
impl TestStruct {
pub fn new() -> Self {
Self { x: 1 }
}
pub fn update(&mut self) {
self.x += 1000;
}
pub fn calculate(&mut self, data: i64) -> i64 {
self.x * data
}
pub fn get_x(&mut self) -> i64 {
self.x
}
pub fn set_x(&mut self, value: i64) {
self.x = value;
}
}
let mut engine = Engine::new();
2020-10-07 09:55:45 +02:00
engine
2022-02-10 05:54:30 +01:00
.register_type_with_name::<TestStruct>("TestStruct")
2020-12-26 08:41:41 +01:00
.register_fn("new_ts", TestStruct::new)
2022-02-10 05:54:30 +01:00
.register_fn("update", TestStruct::update)
.register_fn("calc", TestStruct::calculate)
.register_get_set("x", TestStruct::get_x, TestStruct::set_x);
#[cfg(feature = "metadata")]
{
println!("Functions registered:");
engine
.gen_fn_signatures(false)
.into_iter()
.for_each(|func| println!("{}", func));
println!();
}
2022-02-10 05:54:30 +01:00
let result = engine.eval::<i64>(
2021-04-20 06:01:35 +02:00
"
2021-02-20 16:46:25 +01:00
let x = new_ts();
2022-02-10 05:54:30 +01:00
x.x = 42;
2021-02-20 16:46:25 +01:00
x.update();
2022-02-10 05:54:30 +01:00
x.calc(x.x)
2021-02-20 16:46:25 +01:00
",
)?;
2020-03-09 14:09:53 +01:00
2022-02-10 05:54:30 +01:00
println!("result: {}", result); // prints 1085764
2020-03-09 14:09:53 +01:00
Ok(())
}