diff --git a/examples/custom_types_and_methods.rs b/examples/custom_types_and_methods.rs new file mode 100644 index 00000000..94641009 --- /dev/null +++ b/examples/custom_types_and_methods.rs @@ -0,0 +1,30 @@ +extern crate rhai; +use rhai::{Engine, FnRegister}; + +#[derive(Debug, Clone)] +struct TestStruct { + x: i32 +} + +impl TestStruct { + fn update(&mut self) { + self.x += 1000; + } + + fn new() -> TestStruct { + TestStruct { x: 1 } + } +} + +fn main() { + let mut engine = Engine::new(); + + engine.register_type::(); + + &(TestStruct::update as fn(&mut TestStruct)->()).register(&mut engine, "update"); + &(TestStruct::new as fn()->TestStruct).register(&mut engine, "new_ts"); + + if let Ok(result) = engine.eval("var x = new_ts(); x.update(); x".to_string()).unwrap().downcast::() { + println!("result: {}", result.x); // prints 1001 + } +} \ No newline at end of file diff --git a/examples/hello.rs b/examples/hello.rs new file mode 100644 index 00000000..d90f198a --- /dev/null +++ b/examples/hello.rs @@ -0,0 +1,10 @@ +extern crate rhai; +use rhai::Engine; + +fn main() { + let mut engine = Engine::new(); + + if let Ok(result) = engine.eval("40 + 2".to_string()).unwrap().downcast::() { + println!("Answer: {}", *result); // prints 42 + } +} \ No newline at end of file diff --git a/examples/simple_fn.rs b/examples/simple_fn.rs new file mode 100644 index 00000000..bc8badb7 --- /dev/null +++ b/examples/simple_fn.rs @@ -0,0 +1,16 @@ +extern crate rhai; +use rhai::{Engine, FnRegister}; + +fn add(x: i32, y: i32) -> i32 { + x + y +} + +fn main() { + let mut engine = Engine::new(); + + &(add as fn(x: i32, y: i32)->i32).register(&mut engine, "add"); + + if let Ok(result) = engine.eval("add(40, 2)".to_string()).unwrap().downcast::() { + println!("Answer: {}", *result); // prints 42 + } +} diff --git a/src/engine.rs b/src/engine.rs index 1e66575e..9e02fae1 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -313,7 +313,7 @@ impl Engine { } } - fn register_type(&mut self) { + pub fn register_type(&mut self) { fn clone_helper(t:T)->T { t.clone() }; &(clone_helper as fn(T)->T).register(self, "clone");