Fix README example for on_print and on_debug.

This commit is contained in:
Stephen Chung 2020-04-29 23:03:18 +08:00
parent 21c3edb31e
commit 60b52c142e
2 changed files with 39 additions and 5 deletions

View File

@ -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<String> = Vec::new();
let logbook = Arc::new(RwLock::new(Vec::<String>::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);
}
```

31
tests/print.rs Normal file
View File

@ -0,0 +1,31 @@
use rhai::{Engine, EvalAltResult};
use std::sync::{Arc, RwLock};
#[test]
fn test_print() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
let logbook = Arc::new(RwLock::new(Vec::<String>::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(())
}