diff --git a/examples/repl.rs b/examples/repl.rs index f18a56e5..81f42158 100644 --- a/examples/repl.rs +++ b/examples/repl.rs @@ -48,6 +48,7 @@ fn print_error(input: &str, err: EvalAltResult) { fn print_help() { println!("help => print this help"); println!("quit, exit => quit"); + println!("scope => print all variables in the scope"); println!("ast => print the last AST"); println!("astu => print the last raw, un-optimized AST"); println!(r"end a line with '\' to continue to the next line."); @@ -110,6 +111,13 @@ fn main() { continue; } "exit" | "quit" => break, // quit + "scope" => { + scope + .iter() + .enumerate() + .for_each(|(i, (name, value))| println!("[{}] {} = {:?}", i + 1, name, value)); + continue; + } "astu" => { // print the last un-optimized AST println!("{:#?}", &ast_u); diff --git a/src/scope.rs b/src/scope.rs index 97d3770e..1c8a43bd 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -444,9 +444,37 @@ impl<'a> Scope<'a> { } /// Get an iterator to entries in the Scope. - pub(crate) fn iter(&self) -> impl Iterator { + pub(crate) fn to_iter(&self) -> impl Iterator { self.0.iter().rev() // Always search a Scope in reverse order } + + /// Get an iterator to entries in the Scope. + /// + /// # Examples + /// + /// ``` + /// use rhai::{Dynamic, Scope}; + /// + /// let mut my_scope = Scope::new(); + /// + /// my_scope.push("x", 42_i64); + /// my_scope.push("foo", "hello".to_string()); + /// + /// let mut iter = my_scope.iter(); + /// + /// let (name, value) = iter.next().unwrap(); + /// assert_eq!(name, "x"); + /// assert_eq!(value.clone().cast::(), 42); + /// + /// let (name, value) = iter.next().unwrap(); + /// assert_eq!(name, "foo"); + /// assert_eq!(value.clone().cast::(), "hello"); + /// ``` + pub fn iter(&self) -> impl Iterator { + self.0 + .iter() + .map(|Entry { name, value, .. }| (name.as_ref(), value)) + } } impl<'a, K: Into>> iter::Extend<(K, EntryType, Dynamic)> for Scope<'a> {