This repository has been archived on 2025-08-04. You can view files and clone it, but cannot push or open issues or pull requests.
rhaj/rhai_engine/examples/loadscripts/test_dynamic_loading.rs
2025-04-03 13:12:08 +02:00

99 lines
3.1 KiB
Rust

use std::collections::HashMap;
use rhai::Dynamic;
use rhai_engine::ScriptManager;
use std::path::Path;
/// Test the dynamic loading of Rhai scripts and functions
pub fn main() -> Result<(), String> {
println!("\n=== TESTING DYNAMIC FUNCTION LOADING ===\n");
// Create a new ScriptManager
let mut script_manager = ScriptManager::new();
println!("Loading Rhai scripts from scripts directory...");
// Get the scripts directory path
let scripts_dir = Path::new("examples/loadscripts/scripts");
// Use the ScriptManager to load all scripts from the directory
let loaded_scripts = script_manager.load_scripts_from_directory(scripts_dir)?;
// Print loaded scripts
println!("\nLoaded scripts:");
for script in &loaded_scripts {
println!(" - {}", script);
}
// Get all available functions using the get_function_names method
let function_names = script_manager.get_function_names();
// Print all available functions
println!("\nAll available functions:");
for name in &function_names {
println!(" - {}", name);
}
// Group functions by their script prefix to display nicely
let scripts = group_functions_by_script(&function_names);
// Display functions by script
display_functions_by_script(&scripts);
// Test some functions from each script
println!("\nDynamic function testing:");
//TODO: should not start with string_utils we want capitalize as function usable as is
script_manager.run( "string_utils:capitalize(hello world);")?;
script_manager.run( "math_utils:format_number(1234567);")?;
// Test evaluating a complex script
println!("\nEvaluating a complex script:");
let complex_script = r#"
let sentence = "Count the words in this sentence";
let count = test_utils:count_words(sentence);
print("Word count: " + truncate("count",1));
count * 2 // Return double the word count
"#;
// Evaluate the script
println!("```\n{}\n```", complex_script);
match script_manager.eval::<Dynamic>(complex_script) {
Ok(result) => println!(" Result: {}", result),
Err(e) => println!(" Error: {}", e)
}
println!("\n=== DYNAMIC FUNCTION LOADING TEST COMPLETE ===\n");
Ok(())
}
// Helper function to group functions by script
fn group_functions_by_script(function_names: &[String]) -> HashMap<String, Vec<String>> {
let mut scripts = HashMap::new();
for name in function_names {
let parts: Vec<&str> = name.split(':').collect();
if parts.len() == 2 {
let script = parts[0].to_string();
let func = parts[1].to_string();
scripts.entry(script).or_insert_with(Vec::new).push(func);
}
}
scripts
}
// Helper function to display functions grouped by script
fn display_functions_by_script(scripts: &HashMap<String, Vec<String>>) {
println!("\nFunctions by script:");
for (script, funcs) in scripts {
println!(" {}:", script);
for func in funcs {
println!(" - {}", func);
}
}
}