Skip to main content

Scope

Struct Scope 

Source
pub struct Scope<'a> { /* private fields */ }
Available on crate feature rhai only.
Expand description

Type containing information about the current scope. Useful for keeping state between Engine evaluation runs.

§Lifetime

Currently the lifetime parameter is not used, but it is not guaranteed to remain unused for future versions. Until then, 'static can be used.

§Thread Safety

Currently, Scope is neither Send nor Sync. Turn on the sync feature to make it Send + Sync.

§Example

use rhai::{Engine, Scope};

let engine = Engine::new();
let mut my_scope = Scope::new();

my_scope.push("z", 40_i64);

engine.run_with_scope(&mut my_scope, "let x = z + 1; z = 0;")?;

let result: i64 = engine.eval_with_scope(&mut my_scope, "x + 1")?;

assert_eq!(result, 42);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 41);
assert_eq!(my_scope.get_value::<i64>("z").expect("z should exist"), 0);

When searching for entries, newly-added entries are found before similarly-named but older entries, allowing for automatic shadowing.

Implementations§

Source§

impl Scope<'_>

Source

pub fn new() -> Scope<'_>

Create a new Scope.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn with_capacity(capacity: usize) -> Scope<'_>

Create a new Scope with a particular capacity.

§Example
use rhai::Scope;

let mut my_scope = Scope::with_capacity(10);

my_scope.push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn clear(&mut self) -> &mut Scope<'_>

Empty the Scope.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert!(my_scope.contains("x"));
assert_eq!(my_scope.len(), 1);
assert!(!my_scope.is_empty());

my_scope.clear();
assert!(!my_scope.contains("x"));
assert_eq!(my_scope.len(), 0);
assert!(my_scope.is_empty());
Source

pub fn len(&self) -> usize

Get the number of entries inside the Scope.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();
assert_eq!(my_scope.len(), 0);

my_scope.push("x", 42_i64);
assert_eq!(my_scope.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true if this Scope contains no variables.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();
assert!(my_scope.is_empty());

my_scope.push("x", 42_i64);
assert!(!my_scope.is_empty());
Source

pub fn push( &mut self, name: impl Into<SmartString<LazyCompact>>, value: impl Variant + Clone, ) -> &mut Scope<'_>

Add (push) a new entry to the Scope.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn push_dynamic( &mut self, name: impl Into<SmartString<LazyCompact>>, value: Dynamic, ) -> &mut Scope<'_>

Add (push) a new Dynamic entry to the Scope.

§Example
use rhai::{Dynamic,  Scope};

let mut my_scope = Scope::new();

my_scope.push_dynamic("x", Dynamic::from(42_i64));
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn push_constant( &mut self, name: impl Into<SmartString<LazyCompact>>, value: impl Variant + Clone, ) -> &mut Scope<'_>

Add (push) a new constant to the Scope.

Constants are immutable and cannot be assigned to. Their values never change. Constants propagation is a technique used to optimize an AST.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push_constant("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn push_constant_dynamic( &mut self, name: impl Into<SmartString<LazyCompact>>, value: Dynamic, ) -> &mut Scope<'_>

Add (push) a new constant with a Dynamic value to the Scope.

Constants are immutable and cannot be assigned to. Their values never change. Constants propagation is a technique used to optimize an AST.

§Example
use rhai::{Dynamic, Scope};

let mut my_scope = Scope::new();

my_scope.push_constant_dynamic("x", Dynamic::from(42_i64));
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn pop(&mut self) -> &mut Scope<'_>

Remove the last entry from the Scope.

§Panics

Panics is the Scope is empty.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
my_scope.push("y", 123_i64);
assert!(my_scope.contains("x"));
assert!(my_scope.contains("y"));
assert_eq!(my_scope.len(), 2);

my_scope.pop();
assert!(my_scope.contains("x"));
assert!(!my_scope.contains("y"));
assert_eq!(my_scope.len(), 1);

my_scope.pop();
assert!(!my_scope.contains("x"));
assert!(!my_scope.contains("y"));
assert_eq!(my_scope.len(), 0);
assert!(my_scope.is_empty());
Source

pub fn rewind(&mut self, size: usize) -> &mut Scope<'_>

Truncate (rewind) the Scope to a previous size.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
my_scope.push("y", 123_i64);
assert!(my_scope.contains("x"));
assert!(my_scope.contains("y"));
assert_eq!(my_scope.len(), 2);

my_scope.rewind(1);
assert!(my_scope.contains("x"));
assert!(!my_scope.contains("y"));
assert_eq!(my_scope.len(), 1);

my_scope.rewind(0);
assert!(!my_scope.contains("x"));
assert!(!my_scope.contains("y"));
assert_eq!(my_scope.len(), 0);
assert!(my_scope.is_empty());
Source

pub fn contains(&self, name: &str) -> bool

Does the Scope contain the entry?

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert!(my_scope.contains("x"));
assert!(!my_scope.contains("y"));
Source

pub fn get_value<T>(&self, name: &str) -> Option<T>
where T: Variant + Clone,

Get the value of an entry in the Scope, starting from the last.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
Source

pub fn get_value_ref<T>(&self, name: &str) -> Option<&T>
where T: Variant + Clone,

Get a reference the value of an entry in the Scope, starting from the last.

§Panics

Panics if the value is shared.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);

let ptr = my_scope.get_value_ref::<i64>("x").expect("x should exist");

assert_eq!(*ptr, 42);
Source

pub fn get_value_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Variant + Clone,

Get a mutable reference the value of an entry in the Scope, starting from the last.

§Panics

Panics if the value is shared.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);

let ptr = my_scope.get_value_mut::<i64>("x").expect("x should exist");

*ptr = 0;

assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 0);
Source

pub fn is_constant(&self, name: &str) -> Option<bool>

Check if the named entry in the Scope is constant.

Search starts backwards from the last, stopping at the first entry matching the specified name.

Returns None if no entry matching the specified name is found.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push_constant("x", 42_i64);
assert_eq!(my_scope.is_constant("x"), Some(true));
assert_eq!(my_scope.is_constant("y"), None);
Source

pub fn set_or_push( &mut self, name: impl AsRef<str> + Into<SmartString<LazyCompact>>, value: impl Variant + Clone, ) -> &mut Scope<'_>

Update the value of the named entry in the Scope if it already exists and is not constant. Push a new entry with the value into the Scope if the name doesn’t exist or if the existing entry is constant.

Search starts backwards from the last, and only the first entry matching the specified name is updated.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.set_or_push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);
assert_eq!(my_scope.len(), 1);

my_scope.set_or_push("x", 0_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 0);
assert_eq!(my_scope.len(), 1);

my_scope.set_or_push("y", 123_i64);
assert_eq!(my_scope.get_value::<i64>("y").expect("y should exist"), 123);
assert_eq!(my_scope.len(), 2);
Source

pub fn set_value( &mut self, name: impl AsRef<str> + Into<SmartString<LazyCompact>>, value: impl Variant + Clone, ) -> &mut Scope<'_>

Update the value of the named entry in the Scope.

Search starts backwards from the last, and only the first entry matching the specified name is updated. If no entry matching the specified name is found, a new one is added.

§Panics

Panics when trying to update the value of a constant.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);

my_scope.set_value("x", 0_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 0);
Source

pub fn get(&self, name: &str) -> Option<&Dynamic>

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());
Source

pub fn remove<T>(&mut self, name: &str) -> Option<T>
where T: Variant + Clone,

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);
Source

pub fn get_mut(&mut self, name: &str) -> Option<&mut Dynamic>

Get a mutable reference to the value of an entry in the Scope.

If the entry by the specified name is not found, or if it is read-only, None is returned.

§Example
use rhai::Scope;

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 42);

let ptr = my_scope.get_mut("x").expect("x should exist");
*ptr = 123_i64.into();

assert_eq!(my_scope.get_value::<i64>("x").expect("x should exist"), 123);

my_scope.push_constant("z", 1_i64);
assert!(my_scope.get_mut("z").is_none());
Source

pub fn set_alias( &mut self, name: impl AsRef<str> + Into<SmartString<LazyCompact>>, alias: impl Into<ImmutableString>, )

Available on non-crate feature no_module only.

Add an alias to a variable in the Scope so that it is exported under that name. This is an advanced API.

Variable aliases are used, for example, in Module::eval_ast_as_new to create a new module with exported variables under different names.

If the alias is empty, then the variable is exported under its original name.

Multiple aliases can be added to any variable.

Only the last variable matching the name (and not other shadowed versions) is aliased by this call.

Source

pub fn clone_visible(&self) -> Scope<'_>

Clone the Scope, keeping only the last instances of each variable name. Shadowed variables are omitted in the copy.

Source

pub fn iter(&self) -> impl Iterator<Item = (&str, bool, Dynamic)>

Get an iterator to entries in the Scope. Shared values are flatten-cloned.

§Example
use rhai::{Dynamic, Scope};

let mut my_scope = Scope::new();

my_scope.push("x", 42_i64);
my_scope.push_constant("foo", "hello");

let mut iter = my_scope.iter();

let (name, is_constant, value) = iter.next().expect("value should exist");
assert_eq!(name, "x");
assert!(!is_constant);
assert_eq!(value.cast::<i64>(), 42);

let (name, is_constant, value) = iter.next().expect("value should exist");
assert_eq!(name, "foo");
assert!(is_constant);
assert_eq!(value.cast::<String>(), "hello");
Source

pub fn iter_raw(&self) -> impl Iterator<Item = (&str, bool, &Dynamic)>

Get an iterator to entries in the Scope. Shared values are not expanded.

Trait Implementations§

Source§

impl Clone for Scope<'_>

Source§

fn clone(&self) -> Scope<'_>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for Scope<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'a> Default for Scope<'a>

Source§

fn default() -> Scope<'a>

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Scope<'_>

Source§

fn deserialize<D>( deserializer: D, ) -> Result<Scope<'_>, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Scope<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<K> Extend<(K, Dynamic)> for Scope<'_>

Source§

fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = (K, Dynamic)>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<K> Extend<(K, bool, Dynamic)> for Scope<'_>

Source§

fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = (K, bool, Dynamic)>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<K> FromIterator<(K, Dynamic)> for Scope<'_>

Source§

fn from_iter<T>(iter: T) -> Scope<'_>
where T: IntoIterator<Item = (K, Dynamic)>,

Creates a value from an iterator. Read more
Source§

impl<K> FromIterator<(K, bool, Dynamic)> for Scope<'_>

Source§

fn from_iter<T>(iter: T) -> Scope<'_>
where T: IntoIterator<Item = (K, bool, Dynamic)>,

Creates a value from an iterator. Read more
Source§

impl<'a> Hash for Scope<'a>

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl IntoIterator for Scope<'_>

Source§

type Item = (String, Dynamic, Vec<ImmutableString>)

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = <Scope<'_> as IntoIterator>::Item>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <Scope<'_> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a Scope<'_>

Source§

type Item = (&'a str, &'a Dynamic, &'a [ImmutableString])

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = <&'a Scope<'_> as IntoIterator>::Item> + 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <&'a Scope<'_> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl Serialize for Scope<'_>

Source§

fn serialize<S>( &self, ser: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Scope<'a>

§

impl<'a> !UnwindSafe for Scope<'a>

§

impl<'a> Freeze for Scope<'a>

§

impl<'a> Send for Scope<'a>

§

impl<'a> Sync for Scope<'a>

§

impl<'a> Unpin for Scope<'a>

§

impl<'a> UnsafeUnpin for Scope<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromBase64 for T
where T: for<'de> Deserialize<'de>,

Source§

fn from_base64<Input>(raw: &Input) -> Result<T, Error>
where Input: AsRef<[u8]> + ?Sized,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ServiceExt for T

Source§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Available on crate feature map-response-body only.
Apply a transformation to the response body. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using gRPC headers. Read more
Source§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Available on crate feature follow-redirect only.
Follow redirect resposes using the Standard policy. Read more
Source§

impl<C> SignWithKey<String> for C
where C: ToBase64,

Source§

impl<T> ToBase64 for T
where T: Serialize,

Source§

fn to_base64(&self) -> Result<Cow<'_, str>, Error>

Source§

impl<T> ToJmespath for T
where T: Serialize,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> Variant for T
where T: Any + Clone + SendSync,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert this Variant trait object to &dyn Any.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert this Variant trait object to &mut dyn Any.
Source§

fn as_boxed_any(self: Box<T>) -> Box<dyn Any>

Convert this Variant trait object to Box<dyn Any>.
Source§

fn type_name(&self) -> &'static str

Get the name of this type.
Source§

fn clone_object(&self) -> Box<dyn Variant>

Clone this Variant trait object.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more