From 21f822020fe5052c70cdc8e078173119805d51eb Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 27 Jul 2022 11:35:40 +0800 Subject: [PATCH] Add Scope::remove. --- CHANGELOG.md | 1 + src/types/scope.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c81c5682..297abdb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ Enhancements * `as_string` is added to BLOB's to convert it into a string by interpreting it as a UTF-8 byte stream. * `FnAccess::is_private`, `FnAccess::is_public`, `FnNamespace::is_module_namespace` and `FnNameSpace::is_global_namespace` are added for convenience. * `Iterator` type for functions metadata is simplified to `Iterator`. +* `Scope::remove` is added to remove a variable from a `Scope`, returning its value. Version 1.8.0 diff --git a/src/types/scope.rs b/src/types/scope.rs index 41e40afe..5f92188d 100644 --- a/src/types/scope.rs +++ b/src/types/scope.rs @@ -550,6 +550,41 @@ impl Scope<'_> { pub fn get(&self, name: &str) -> Option<&Dynamic> { self.get_index(name).map(|(index, _)| &self.values[index]) } + /// Remove the last entry in the [`Scope`] by the specified name and return its value. + /// + /// 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", 123_i64); // first 'x' + /// my_scope.push("x", 42_i64); // second 'x', shadows first + /// + /// assert_eq!(my_scope.len(), 2); + /// + /// let value = my_scope.remove::("x").expect("x should exist"); + /// + /// assert_eq!(value, 42); + /// + /// assert_eq!(my_scope.len(), 1); + /// + /// let value = my_scope.get_value::("x").expect("x should still exist"); + /// + /// assert_eq!(value, 123); + /// ``` + #[inline(always)] + #[must_use] + pub fn remove(&mut self, name: &str) -> Option { + self.get_index(name).and_then(|(index, _)| { + self.names.remove(index); + self.aliases.remove(index); + self.values.remove(index).try_cast() + }) + } /// Get a mutable reference to an entry in the [`Scope`]. /// /// If the entry by the specified name is not found, or if it is read-only,