From 60b52c142e793e78e731662dc63f3995e3a361c2 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 29 Apr 2020 23:03:18 +0800 Subject: [PATCH] Fix README example for on_print and on_debug. --- README.md | 13 ++++++++----- tests/print.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 tests/print.rs diff --git a/README.md b/README.md index 0e8d4b77..f89bc940 100644 --- a/README.md +++ b/README.md @@ -1979,17 +1979,20 @@ engine.on_print(|x| println!("hello: {}", x)); engine.on_debug(|x| println!("DEBUG: {}", x)); // Example: quick-'n-dirty logging -let mut log: Vec = Vec::new(); +let logbook = Arc::new(RwLock::new(Vec::::new())); // Redirect print/debug output to 'log' -engine.on_print(|s| log.push(format!("entry: {}", s))); -engine.on_debug(|s| log.push(format!("DEBUG: {}", s))); +let log = logbook.clone(); +engine.on_print(move |s| log.write().unwrap().push(format!("entry: {}", s))); + +let log = logbook.clone(); +engine.on_debug(move |s| log.write().unwrap().push(format!("DEBUG: {}", s))); // Evaluate script engine.eval::<()>(script)?; -// 'log' captures all the 'print' and 'debug' output -for entry in log { +// 'logbook' captures all the 'print' and 'debug' output +for entry in logbook.read().unwrap().iter() { println!("{}", entry); } ``` diff --git a/tests/print.rs b/tests/print.rs new file mode 100644 index 00000000..ec707e8b --- /dev/null +++ b/tests/print.rs @@ -0,0 +1,31 @@ +use rhai::{Engine, EvalAltResult}; +use std::sync::{Arc, RwLock}; + +#[test] +fn test_print() -> Result<(), Box> { + let mut engine = Engine::new(); + + let logbook = Arc::new(RwLock::new(Vec::::new())); + + // Redirect print/debug output to 'log' + let log = logbook.clone(); + engine.on_print(move |s| log.write().unwrap().push(format!("entry: {}", s))); + + let log = logbook.clone(); + engine.on_debug(move |s| log.write().unwrap().push(format!("DEBUG: {}", s))); + + // Evaluate script + engine.eval::<()>("print(40 + 2)")?; + engine.eval::<()>(r#"debug("hello!")"#)?; + + // 'logbook' captures all the 'print' and 'debug' output + assert_eq!(logbook.read().unwrap().len(), 2); + assert_eq!(logbook.read().unwrap()[0], "entry: 42"); + assert_eq!(logbook.read().unwrap()[1], r#"DEBUG: "hello!""#); + + for entry in logbook.read().unwrap().iter() { + println!("{}", entry); + } + + Ok(()) +}