2020-06-20 12:06:17 +08:00
|
|
|
Custom Type Getters and Setters
|
|
|
|
==============================
|
|
|
|
|
|
|
|
{{#include ../links.md}}
|
|
|
|
|
|
|
|
A custom type can also expose members by registering `get` and/or `set` functions.
|
|
|
|
|
|
|
|
```rust
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct TestStruct {
|
|
|
|
field: String
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TestStruct {
|
|
|
|
// Returning a 'String' is OK - Rhai converts it into 'ImmutableString'
|
|
|
|
fn get_field(&mut self) -> String {
|
|
|
|
self.field.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remember Rhai uses 'ImmutableString' or '&str' instead of 'String'
|
|
|
|
fn set_field(&mut self, new_val: ImmutableString) {
|
|
|
|
// Get a 'String' from an 'ImmutableString'
|
|
|
|
self.field = (*new_val).clone();
|
|
|
|
}
|
|
|
|
|
|
|
|
fn new() -> Self {
|
|
|
|
TestStruct { field: "hello" }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-22 22:02:49 +08:00
|
|
|
let mut engine = Engine::new();
|
2020-06-20 12:06:17 +08:00
|
|
|
|
|
|
|
engine.register_type::<TestStruct>();
|
|
|
|
|
|
|
|
engine.register_get_set("xyz", TestStruct::get_field, TestStruct::set_field);
|
|
|
|
engine.register_fn("new_ts", TestStruct::new);
|
|
|
|
|
|
|
|
// Return result can be 'String' - Rhai will automatically convert it from 'ImmutableString'
|
|
|
|
let result = engine.eval::<String>(r#"let a = new_ts(); a.xyz = "42"; a.xyz"#)?;
|
|
|
|
|
|
|
|
println!("Answer: {}", result); // prints 42
|
|
|
|
```
|