Skip to content

Commit 2491f54

Browse files
committed
start writing marshalling code for rhai
1 parent 5b34eea commit 2491f54

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,53 @@
1+
use std::str::FromStr;
12

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

Comments
 (0)