2022-02-12 12:41:04 +08:00
|
|
|
//! An example showing how to register a Rust type and use it with arrays.
|
|
|
|
|
2022-01-11 22:12:46 +08:00
|
|
|
use rhai::{Engine, EvalAltResult};
|
2016-04-13 18:40:06 -07:00
|
|
|
|
2022-01-16 22:50:39 +08:00
|
|
|
#[cfg(not(feature = "no_index"))]
|
|
|
|
#[cfg(not(feature = "no_object"))]
|
2020-12-26 15:41:41 +08:00
|
|
|
fn main() -> Result<(), Box<EvalAltResult>> {
|
2022-02-10 12:54:30 +08:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
struct TestStruct {
|
|
|
|
x: i64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TestStruct {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self { x: 1 }
|
|
|
|
}
|
|
|
|
pub fn update(&mut self) {
|
|
|
|
self.x += 1000;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-13 18:40:06 -07:00
|
|
|
let mut engine = Engine::new();
|
|
|
|
|
2020-10-07 15:55:45 +08:00
|
|
|
engine
|
2022-02-10 12:54:30 +08:00
|
|
|
.register_type_with_name::<TestStruct>("TestStruct")
|
2020-12-26 15:41:41 +08:00
|
|
|
.register_fn("new_ts", TestStruct::new)
|
|
|
|
.register_fn("update", TestStruct::update);
|
2016-04-13 18:40:06 -07:00
|
|
|
|
2022-02-10 12:54:30 +08:00
|
|
|
#[cfg(feature = "metadata")]
|
|
|
|
{
|
|
|
|
println!("Functions registered:");
|
|
|
|
|
|
|
|
engine
|
|
|
|
.gen_fn_signatures(false)
|
|
|
|
.into_iter()
|
|
|
|
.for_each(|func| println!("{}", func));
|
|
|
|
|
|
|
|
println!();
|
|
|
|
}
|
|
|
|
|
2021-02-20 23:46:25 +08:00
|
|
|
let result = engine.eval::<TestStruct>(
|
2021-04-20 12:01:35 +08:00
|
|
|
"
|
2021-02-20 23:46:25 +08:00
|
|
|
let x = new_ts();
|
|
|
|
x.update();
|
|
|
|
x
|
|
|
|
",
|
|
|
|
)?;
|
|
|
|
|
|
|
|
println!("{:?}", result);
|
|
|
|
|
|
|
|
let result = engine.eval::<TestStruct>(
|
2021-04-20 12:01:35 +08:00
|
|
|
"
|
2021-02-20 23:46:25 +08:00
|
|
|
let x = [ new_ts() ];
|
|
|
|
x[0].update();
|
|
|
|
x[0]
|
|
|
|
",
|
|
|
|
)?;
|
|
|
|
|
|
|
|
println!("{:?}", result);
|
2020-12-26 15:41:41 +08:00
|
|
|
|
|
|
|
Ok(())
|
2016-04-13 18:40:06 -07:00
|
|
|
}
|
2022-01-16 22:50:39 +08:00
|
|
|
|
|
|
|
#[cfg(any(feature = "no_index", feature = "no_object"))]
|
|
|
|
fn main() {
|
|
|
|
panic!("This example does not run under 'no_index' or 'no_object'.")
|
|
|
|
}
|