91 lines
2.3 KiB
Rust
91 lines
2.3 KiB
Rust
use rhai::{Engine, EvalAltResult};
|
|
use rhai_autobind_macros::rhai_autobind;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::path::Path;
|
|
|
|
// Define a simple Calculator struct with the rhai_autobind attribute
|
|
#[derive(Debug, Clone, Serialize, Deserialize, rhai::CustomType)]
|
|
#[rhai_autobind]
|
|
pub struct Calculator {
|
|
pub value: f64,
|
|
}
|
|
|
|
impl Calculator {
|
|
// Constructor
|
|
pub fn new() -> Self {
|
|
Calculator { value: 0.0 }
|
|
}
|
|
|
|
// Add method
|
|
pub fn add(&mut self, x: f64) -> f64 {
|
|
self.value += x;
|
|
self.value
|
|
}
|
|
|
|
// Subtract method
|
|
pub fn subtract(&mut self, x: f64) -> f64 {
|
|
self.value -= x;
|
|
self.value
|
|
}
|
|
|
|
// Multiply method
|
|
pub fn multiply(&mut self, x: f64) -> f64 {
|
|
self.value *= x;
|
|
self.value
|
|
}
|
|
|
|
// Divide method
|
|
pub fn divide(&mut self, x: f64) -> f64 {
|
|
if x == 0.0 {
|
|
println!("Error: Division by zero!");
|
|
return self.value;
|
|
}
|
|
self.value /= x;
|
|
self.value
|
|
}
|
|
|
|
// Clear method
|
|
pub fn clear(&mut self) -> f64 {
|
|
self.value = 0.0;
|
|
self.value
|
|
}
|
|
|
|
// Get value method
|
|
pub fn get_value(&self) -> f64 {
|
|
self.value
|
|
}
|
|
}
|
|
|
|
fn main() -> Result<(), Box<EvalAltResult>> {
|
|
println!("Rhai Calculator Example");
|
|
println!("======================");
|
|
|
|
// Create a new Rhai engine
|
|
let mut engine = Engine::new();
|
|
|
|
// Register the Calculator type with the engine using the generated function
|
|
Calculator::register_rhai_bindings_for_calculator(&mut engine);
|
|
|
|
// Register print function for output
|
|
engine.register_fn("println", |s: &str| println!("{}", s));
|
|
|
|
// Create a calculator instance to demonstrate it works
|
|
let calc = Calculator::new();
|
|
println!("Initial value: {}", calc.value);
|
|
|
|
// Load and run the Rhai script
|
|
let script_path = Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
.join("examples")
|
|
.join("rhai_autobind_example")
|
|
.join("calculator.rhai");
|
|
|
|
println!("Loading Rhai script from: {}", script_path.display());
|
|
|
|
match engine.eval_file::<()>(script_path) {
|
|
Ok(_) => println!("Script executed successfully"),
|
|
Err(e) => eprintln!("Error executing script: {}\nAt: {:?}", e, e.position()),
|
|
}
|
|
|
|
Ok(())
|
|
}
|