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("rhai_engine/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:"); // Test string_utils functions test_function(&script_manager, "string_utils:capitalize", vec![Dynamic::from("hello world")])?; // Test math_utils functions test_function(&script_manager, "math_utils:format_number", vec![Dynamic::from(1234567)])?; // Test test_utils functions test_function(&script_manager, "test_utils:reverse_string", vec![Dynamic::from("hello world")])?; test_function(&script_manager, "test_utils:count_words", vec![Dynamic::from("this is a test sentence")])?; test_function(&script_manager, "test_utils:factorial", vec![Dynamic::from(5)])?; 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> { 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>) { println!("\nFunctions by script:"); for (script, funcs) in scripts { println!(" {}:", script); for func in funcs { println!(" - {}", func); } } } // Helper function to test a function and display its result fn test_function(script_manager: &ScriptManager, name: &str, args: Vec) -> Result<(), String> { let result = script_manager.call_function(name, args)?; println!(" {}() => {}", name, result); Ok(()) }