|
| 1 | +use std::str::FromStr; |
1 | 2 |
|
| 3 | +use bevy_mod_scripting_core::{bindings::script_value::ScriptValue, error::InteropError}; |
| 4 | +use rhai::{Dynamic, EvalAltResult}; |
| 5 | + |
| 6 | +pub trait IntoDynamic { |
| 7 | + fn into_dynamic(self) -> Result<Dynamic, Box<EvalAltResult>>; |
| 8 | +} |
| 9 | + |
| 10 | +impl IntoDynamic for ScriptValue { |
| 11 | + fn into_dynamic(self) -> Result<Dynamic, Box<EvalAltResult>> { |
| 12 | + Ok(match self { |
| 13 | + ScriptValue::Unit => Dynamic::UNIT, |
| 14 | + ScriptValue::Bool(b) => Dynamic::from_bool(b), |
| 15 | + ScriptValue::Integer(i) => Dynamic::from_int(i), |
| 16 | + ScriptValue::Float(f) => Dynamic::from_float(f), |
| 17 | + ScriptValue::String(cow) => Dynamic::from_str(&cow).map_err(|_| { |
| 18 | + EvalAltResult::ErrorSystem( |
| 19 | + "error in converting string to rhai value".to_owned(), |
| 20 | + InteropError::unsupported_operation( |
| 21 | + None, |
| 22 | + Some(Box::new(cow.clone())), |
| 23 | + "string to rhai value".to_owned(), |
| 24 | + ) |
| 25 | + .into(), |
| 26 | + ) |
| 27 | + })?, |
| 28 | + ScriptValue::List(_vec) => todo!(), |
| 29 | + ScriptValue::Reference(_reflect_reference) => todo!(), |
| 30 | + ScriptValue::Function(_dynamic_script_function_mut) => todo!(), |
| 31 | + ScriptValue::Error(_interop_error) => todo!(), |
| 32 | + }) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +pub trait FromDynamic: Sized { |
| 37 | + fn from_dynamic(dynamic: Dynamic) -> Result<Self, Box<EvalAltResult>>; |
| 38 | +} |
| 39 | + |
| 40 | +impl FromDynamic for ScriptValue { |
| 41 | + fn from_dynamic(dynamic: Dynamic) -> Result<Self, Box<EvalAltResult>> { |
| 42 | + match dynamic { |
| 43 | + d if d.is_unit() => Ok(ScriptValue::Unit), |
| 44 | + d if d.is_bool() => Ok(ScriptValue::Bool(d.as_bool().unwrap())), |
| 45 | + d if d.is_int() => Ok(ScriptValue::Integer(d.as_int().unwrap())), |
| 46 | + d if d.is_float() => Ok(ScriptValue::Float(d.as_float().unwrap())), |
| 47 | + d if d.is_string() => Ok(ScriptValue::String( |
| 48 | + d.into_immutable_string().unwrap().to_string().into(), |
| 49 | + )), |
| 50 | + _ => todo!(), |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments