rhai/examples/custom_types_and_methods.rs

44 lines
816 B
Rust
Raw Normal View History

use rhai::{Engine, EvalAltResult};
2020-12-26 08:41:41 +01:00
#[derive(Debug, Clone)]
struct TestStruct {
x: i64,
}
impl TestStruct {
2020-12-26 08:41:41 +01:00
pub fn update(&mut self) {
self.x += 1000;
}
2020-12-26 08:41:41 +01:00
pub fn new() -> Self {
2020-10-19 08:26:15 +02:00
Self { x: 1 }
}
}
#[cfg(not(feature = "no_object"))]
fn main() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
2020-10-07 09:55:45 +02:00
engine
.register_type::<TestStruct>()
2020-12-26 08:41:41 +01:00
.register_fn("new_ts", TestStruct::new)
.register_fn("update", TestStruct::update);
2021-02-20 16:46:25 +01:00
let result = engine.eval::<TestStruct>(
2021-04-20 06:01:35 +02:00
"
2021-02-20 16:46:25 +01:00
let x = new_ts();
x.update();
x
",
)?;
2020-03-09 14:09:53 +01:00
println!("result: {}", result.x); // prints 1001
Ok(())
}
#[cfg(feature = "no_object")]
fn main() {
panic!("This example does not run under 'no_object'.");
}