Fix type register visibility. Add a few more examples

This commit is contained in:
jonathandturner 2016-03-03 11:08:34 -05:00
parent 13c718c794
commit 3dea40a9f7
4 changed files with 57 additions and 1 deletions

View File

@ -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>();
&(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::<TestStruct>() {
println!("result: {}", result.x); // prints 1001
}
}

10
examples/hello.rs Normal file
View File

@ -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::<i32>() {
println!("Answer: {}", *result); // prints 42
}
}

16
examples/simple_fn.rs Normal file
View File

@ -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::<i32>() {
println!("Answer: {}", *result); // prints 42
}
}

View File

@ -313,7 +313,7 @@ impl Engine {
} }
} }
fn register_type<T: Clone+Any>(&mut self) { pub fn register_type<T: Clone+Any>(&mut self) {
fn clone_helper<T: Clone>(t:T)->T { t.clone() }; fn clone_helper<T: Clone>(t:T)->T { t.clone() };
&(clone_helper as fn(T)->T).register(self, "clone"); &(clone_helper as fn(T)->T).register(self, "clone");