rhai/examples/event_handler_js/main.rs

169 lines
4.5 KiB
Rust
Raw Permalink Normal View History

2022-01-16 15:45:25 +01:00
//! Implementation of the Event Handler With State Pattern - JS Style
2022-01-16 16:15:37 +01:00
#[cfg(any(feature = "no_function", feature = "no_object"))]
pub fn main() {
panic!("This example does not run under 'no_function' or 'no_object'.")
}
2022-01-16 15:45:25 +01:00
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_object"))]
pub fn main() {
2022-11-23 04:36:30 +01:00
use rhai::{CallFnOptions, Dynamic, Engine, Map, Scope, AST};
use std::io::{stdin, stdout, Write};
2022-01-16 15:45:25 +01:00
const SCRIPT_FILE: &str = "event_handler_js/script.rhai";
2022-01-16 15:45:25 +01:00
#[derive(Debug)]
struct Handler {
pub engine: Engine,
pub scope: Scope<'static>,
pub states: Dynamic,
pub ast: AST,
}
2022-01-16 15:45:25 +01:00
fn print_scope(scope: &Scope) {
for (i, (name, constant, value)) in scope.iter_raw().enumerate() {
#[cfg(not(feature = "no_closure"))]
let value_is_shared = if value.is_shared() { " (shared)" } else { "" };
#[cfg(feature = "no_closure")]
let value_is_shared = "";
println!(
"[{}] {}{}{} = {:?}",
i + 1,
if constant { "const " } else { "" },
name,
value_is_shared,
*value.read_lock::<Dynamic>().unwrap(),
)
}
println!();
2022-01-28 11:59:18 +01:00
}
2022-01-16 15:45:25 +01:00
println!("Events Handler Example - JS Style");
println!("==================================");
let mut input = String::new();
// Read script file
print!("Script file [{}]: ", SCRIPT_FILE);
stdout().flush().expect("flush stdout");
input.clear();
stdin().read_line(&mut input).expect("read input");
let path = match input.trim() {
"" => SCRIPT_FILE,
path => path,
};
// Create Engine
let engine = Engine::new();
// Use an object map to hold state
let mut states = Map::new();
// Default states can be added
states.insert("bool_state".into(), Dynamic::FALSE);
// Convert the object map into 'Dynamic'
let mut states: Dynamic = states.into();
// Create a custom 'Scope' to hold state
let mut scope = Scope::new();
// Add any system-provided state into the custom 'Scope'.
// Constants can be used to optimize the script.
scope.push_constant("MY_CONSTANT", 42_i64);
// Compile the handler script.
println!("> Loading script file: {path}");
2022-01-16 15:45:25 +01:00
2022-12-30 18:07:39 +01:00
let ast = match engine.compile_file_with_scope(&scope, path.into()) {
2022-01-16 15:45:25 +01:00
Ok(ast) => ast,
Err(err) => {
eprintln!("! Error: {err}");
2022-01-16 15:45:25 +01:00
println!("Cannot continue. Bye!");
return;
}
};
println!("> Script file loaded.");
println!();
println!("quit = exit program");
println!("scope = print scope");
println!("states = print states");
println!("event arg = run function with argument");
println!();
// Run the 'init' function to initialize the state, retaining variables.
let options = CallFnOptions::new()
.eval_ast(false)
.bind_this_ptr(&mut states);
let result = engine.call_fn_with_options::<()>(options, &mut scope, &ast, "init", ());
2022-01-16 15:45:25 +01:00
if let Err(err) = result {
eprintln!("! {err}")
2022-01-16 15:45:25 +01:00
}
// Create handler instance
let mut handler = Handler {
engine,
scope,
states,
ast,
};
// Events loop
loop {
print!("event> ");
stdout().flush().expect("flush stdout");
// Read event
input.clear();
stdin().read_line(&mut input).expect("read input");
let mut fields = input.trim().splitn(2, ' ');
let event = fields.next().expect("event").trim();
let arg = fields.next().unwrap_or("").to_string();
2022-01-16 15:45:25 +01:00
// Process event
match event {
"quit" => break,
"scope" => {
print_scope(&handler.scope);
continue;
}
"states" => {
println!("{:?}", handler.states);
println!();
continue;
}
// Map all other events to function calls
_ => {
let engine = &handler.engine;
let scope = &mut handler.scope;
let ast = &handler.ast;
let options = CallFnOptions::new()
.eval_ast(false)
.bind_this_ptr(&mut handler.states);
2022-01-16 15:45:25 +01:00
let result = engine.call_fn_with_options::<()>(options, scope, ast, event, (arg,));
2022-01-16 15:45:25 +01:00
if let Err(err) = result {
eprintln!("! {err}")
2022-01-16 15:45:25 +01:00
}
}
}
}
println!("Bye!");
}