This commit is contained in:
kristof 2025-04-03 12:35:55 +02:00
parent e16d4270c0
commit d3c5f97469
4 changed files with 78 additions and 22 deletions

View File

@ -11,6 +11,10 @@ path = "src/lib.rs"
name = "rhai_engine"
path = "src/main.rs"
[[bin]]
name = "test_dynamic_loading"
path = "examples/loadscripts/test_dynamic_loading.rs"
[dependencies]
rhai = "1.12.0"
chrono = "0.4"

View File

@ -1,25 +1,31 @@
use crate::tera_integration::RhaiTeraIntegration;
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 test_dynamic_loading() -> Result<(), String> {
pub fn main() -> Result<(), String> {
println!("\n=== TESTING DYNAMIC FUNCTION LOADING ===\n");
// Create a new RhaiTeraIntegration
let mut integration = RhaiTeraIntegration::new();
// Create a new ScriptManager
let mut script_manager = ScriptManager::new();
println!("Loading Rhai scripts...");
println!("Loading Rhai scripts from scripts directory...");
// Load the original scripts
integration.load_script("string_utils", "src/tera_integration/scripts/string_utils.rhai")?;
integration.load_script("math_utils", "src/tera_integration/scripts/math_utils.rhai")?;
// Get the scripts directory path
let scripts_dir = Path::new("rhai_engine/examples/loadscripts/scripts");
// Load the new test script (which wasn't in the original hardcoded lists)
integration.load_script("test_utils", "src/tera_integration/scripts/test_utils.rhai")?;
// Use the ScriptManager to load all scripts from the directory
let loaded_scripts = script_manager.load_scripts_from_directory(scripts_dir)?;
// Get function names
let function_names = integration.get_function_names();
// 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:");
@ -36,19 +42,19 @@ pub fn test_dynamic_loading() -> Result<(), String> {
// Test some functions from each script
println!("\nDynamic function testing:");
// Test original string utils functions
test_function(&integration, "string_utils:capitalize", vec![Dynamic::from("hello world")])?;
// Test string_utils functions
test_function(&script_manager, "string_utils:capitalize", vec![Dynamic::from("hello world")])?;
// Test original math utils functions
test_function(&integration, "math_utils:format_number", vec![Dynamic::from(1234567)])?;
// Test math_utils functions
test_function(&script_manager, "math_utils:format_number", vec![Dynamic::from(1234567)])?;
// Test new functions from test_utils
test_function(&integration, "test_utils:reverse_string", vec![Dynamic::from("hello world")])?;
// Test test_utils functions
test_function(&script_manager, "test_utils:reverse_string", vec![Dynamic::from("hello world")])?;
test_function(&integration, "test_utils:count_words",
test_function(&script_manager, "test_utils:count_words",
vec![Dynamic::from("this is a test sentence")])?;
test_function(&integration, "test_utils:factorial",
test_function(&script_manager, "test_utils:factorial",
vec![Dynamic::from(5)])?;
println!("\n=== DYNAMIC FUNCTION LOADING TEST COMPLETE ===\n");
@ -86,8 +92,8 @@ fn display_functions_by_script(scripts: &HashMap<String, Vec<String>>) {
}
// Helper function to test a function and display its result
fn test_function(integration: &RhaiTeraIntegration, name: &str, args: Vec<Dynamic>) -> Result<(), String> {
let result = integration.call_function(name, args)?;
fn test_function(script_manager: &ScriptManager, name: &str, args: Vec<Dynamic>) -> Result<(), String> {
let result = script_manager.call_function(name, args)?;
println!(" {}() => {}", name, result);
Ok(())
}

View File

@ -0,0 +1,5 @@
// Export the rhailoader module
pub mod rhailoader;
// Export the ScriptManager for direct usage
pub use rhailoader::ScriptManager;

View File

@ -3,6 +3,7 @@ use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::fs;
use std::io;
/// Type alias for a Rhai function that can be called from Rust
pub type RhaiFn = Box<dyn Fn(Vec<Dynamic>) -> Result<Dynamic, String>>;
@ -250,4 +251,44 @@ impl ScriptManager {
Ok(())
}
/// Load all .rhai scripts from a directory
pub fn load_scripts_from_directory(&mut self, dir_path: impl AsRef<Path>) -> Result<Vec<String>, String> {
let dir_path = dir_path.as_ref();
// Check if directory exists
if !dir_path.exists() || !dir_path.is_dir() {
return Err(format!("Directory does not exist or is not a directory: {}", dir_path.display()));
}
// Get all entries in the directory
let entries = fs::read_dir(dir_path)
.map_err(|e| format!("Failed to read directory {}: {}", dir_path.display(), e))?;
let mut loaded_scripts = Vec::new();
// Process each entry
for entry_result in entries {
let entry = entry_result.map_err(|e| format!("Failed to read directory entry: {}", e))?;
let path = entry.path();
// Only process .rhai files
if path.is_file() && path.extension().map_or(false, |ext| ext == "rhai") {
if let Some(stem) = path.file_stem() {
if let Some(script_name) = stem.to_str() {
// Load the script
self.load_script(script_name, &path)?;
loaded_scripts.push(script_name.to_string());
}
}
}
}
Ok(loaded_scripts)
}
/// Get a list of all registered function names
pub fn get_function_names(&self) -> Vec<String> {
self.functions.keys().cloned().collect()
}
}