Add Scope::remove.

This commit is contained in:
Stephen Chung 2022-07-27 11:35:40 +08:00
parent d42c6b69a3
commit 21f822020f
2 changed files with 36 additions and 0 deletions

View File

@ -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<Item=T>` type for functions metadata is simplified to `Iterator<T>`.
* `Scope::remove` is added to remove a variable from a `Scope`, returning its value.
Version 1.8.0

View File

@ -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::<i64>("x").expect("x should exist");
///
/// assert_eq!(value, 42);
///
/// assert_eq!(my_scope.len(), 1);
///
/// let value = my_scope.get_value::<i64>("x").expect("x should still exist");
///
/// assert_eq!(value, 123);
/// ```
#[inline(always)]
#[must_use]
pub fn remove<T: Variant + Clone>(&mut self, name: &str) -> Option<T> {
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,