...
This commit is contained in:
81
examples/rhai_example.rs
Normal file
81
examples/rhai_example.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
//! Example of using the Rhai integration with SAL
|
||||
//!
|
||||
//! This example demonstrates how to use the Rhai scripting language
|
||||
//! with the System Abstraction Layer (SAL) library.
|
||||
|
||||
use rhai::Engine;
|
||||
use sal::rhai;
|
||||
use std::fs;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Create a new Rhai engine
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Register SAL functions with the engine
|
||||
rhai::register(&mut engine)?;
|
||||
|
||||
// Create a test file
|
||||
let test_file = "rhai_test_file.txt";
|
||||
fs::write(test_file, "Hello, Rhai!")?;
|
||||
|
||||
// Create a test directory
|
||||
let test_dir = "rhai_test_dir";
|
||||
if !fs::metadata(test_dir).is_ok() {
|
||||
fs::create_dir(test_dir)?;
|
||||
}
|
||||
|
||||
// Run a Rhai script that uses SAL functions
|
||||
let script = r#"
|
||||
// Check if files exist
|
||||
let file_exists = exist("rhai_test_file.txt");
|
||||
let dir_exists = exist("rhai_test_dir");
|
||||
|
||||
// Get file size
|
||||
let size = file_size("rhai_test_file.txt");
|
||||
|
||||
// Create a new directory
|
||||
let new_dir = "rhai_new_dir";
|
||||
let mkdir_result = mkdir(new_dir);
|
||||
|
||||
// Copy a file
|
||||
let copy_result = copy("rhai_test_file.txt", "rhai_test_dir/copied_file.txt");
|
||||
|
||||
// Find files
|
||||
let files = find_files(".", "*.txt");
|
||||
|
||||
// Return a map with all the results
|
||||
#{
|
||||
file_exists: file_exists,
|
||||
dir_exists: dir_exists,
|
||||
file_size: size,
|
||||
mkdir_result: mkdir_result,
|
||||
copy_result: copy_result,
|
||||
files: files
|
||||
}
|
||||
"#;
|
||||
|
||||
// Evaluate the script and get the results
|
||||
let result = engine.eval::<rhai::Map>(script)?;
|
||||
|
||||
// Print the results
|
||||
println!("Script results:");
|
||||
println!(" File exists: {}", result.get("file_exists").unwrap().clone().cast::<bool>());
|
||||
println!(" Directory exists: {}", result.get("dir_exists").unwrap().clone().cast::<bool>());
|
||||
println!(" File size: {} bytes", result.get("file_size").unwrap().clone().cast::<i64>());
|
||||
println!(" Mkdir result: {}", result.get("mkdir_result").unwrap().clone().cast::<String>());
|
||||
println!(" Copy result: {}", result.get("copy_result").unwrap().clone().cast::<String>());
|
||||
|
||||
// Print the found files
|
||||
let files = result.get("files").unwrap().clone().cast::<rhai::Array>();
|
||||
println!(" Found files:");
|
||||
for file in files {
|
||||
println!(" - {}", file.cast::<String>());
|
||||
}
|
||||
|
||||
// Clean up
|
||||
fs::remove_file(test_file)?;
|
||||
fs::remove_dir_all(test_dir)?;
|
||||
fs::remove_dir_all("rhai_new_dir")?;
|
||||
|
||||
Ok(())
|
||||
}
|
Reference in New Issue
Block a user