diff --git a/CHANGELOG.md b/CHANGELOG.md index 80d2ef52..cfdd0cf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ Enhancements * `Engine::def_tag`, `Engine::def_tag_mut` and `Engine::set_tag` are added to manage a default value for the custom evaluation state, accessible via `EvalState::tag()` (which is the same as `NativeCallContext::tag()`). * Originally, the debugger's custom state uses the same state as `EvalState::tag()` (which is the same as `NativeCallContext::tag()`). It is now split into its own variable accessible under `Debugger::state()`. * Non-borrowed string keys can now be deserialized for object maps via `serde`. +* `Scope::get` is added to get a reference to a variable's value. Version 1.7.0 diff --git a/src/types/scope.rs b/src/types/scope.rs index 6a169bec..860a93e7 100644 --- a/src/types/scope.rs +++ b/src/types/scope.rs @@ -511,9 +511,33 @@ impl Scope<'_> { } self } + /// Get a reference to an entry in the [`Scope`]. + /// + /// If the entry by the specified name is not found, [`None`] is returned. + /// + /// # Example + /// + /// ``` + /// use rhai::Scope; + /// + /// let mut my_scope = Scope::new(); + /// + /// my_scope.push("x", 42_i64); + /// + /// let value = my_scope.get("x").expect("x should exist"); + /// + /// assert_eq!(value.as_int().unwrap(), 42); + /// + /// assert!(my_scope.get("z").is_none()); + /// ``` + #[inline(always)] + #[must_use] + pub fn get(&self, name: &str) -> Option<&Dynamic> { + self.get_index(name).map(|(index, _)| &self.values[index]) + } /// Get a mutable reference to an entry in the [`Scope`]. /// - /// If the entry by the specified name is not found, of if it is read-only, + /// If the entry by the specified name is not found, or if it is read-only, /// [`None`] is returned. /// /// # Example @@ -531,8 +555,8 @@ impl Scope<'_> { /// /// assert_eq!(my_scope.get_value::("x").expect("x should exist"), 123); /// - /// my_scope.push_constant("Z", 1_i64); - /// assert!(my_scope.get_mut("Z").is_none()); + /// my_scope.push_constant("z", 1_i64); + /// assert!(my_scope.get_mut("z").is_none()); /// ``` #[inline] #[must_use]