Add Dynamic::from(&str)

This commit is contained in:
Stephen Chung 2020-10-06 21:25:05 +08:00
parent 1de44c7ecd
commit 8809d25d3c
3 changed files with 23 additions and 1 deletions

View File

@ -19,6 +19,7 @@ New features
* `OptimizationLevel::Simple` now eagerly evaluates built-in binary operators of primary types (if not overloaded).
* Added `is_def_var()` to detect if variable is defined, and `is_def_fn()` to detect if script function is defined.
* `Dynamic::from(&str)` now constructs a `Dynamic` with a copy of the string as value.
Version 0.19.0

View File

@ -572,6 +572,12 @@ impl Dynamic {
.clone()
.into();
}
if TypeId::of::<T>() == TypeId::of::<&str>() {
return <dyn Any>::downcast_ref::<&str>(&value)
.unwrap()
.to_string()
.into();
}
if TypeId::of::<T>() == TypeId::of::<()>() {
return ().into();
}

View File

@ -1,4 +1,4 @@
use rhai::{Engine, EvalAltResult, ImmutableString, RegisterFn, INT};
use rhai::{Dynamic, Engine, EvalAltResult, ImmutableString, RegisterFn, Scope, INT};
#[test]
fn test_string() -> Result<(), Box<EvalAltResult>> {
@ -49,6 +49,21 @@ fn test_string() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
fn test_string_dynamic() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
let mut scope = Scope::new();
scope.push("x", Dynamic::from("foo"));
scope.push("y", String::from("foo"));
scope.push("z", "foo");
assert!(engine.eval_with_scope::<bool>(&mut scope, r#"x == "foo""#)?);
assert!(engine.eval_with_scope::<bool>(&mut scope, r#"y == "foo""#)?);
assert!(engine.eval_with_scope::<bool>(&mut scope, r#"z == "foo""#)?);
Ok(())
}
#[cfg(not(feature = "no_object"))]
#[test]
fn test_string_substring() -> Result<(), Box<EvalAltResult>> {