Add support for operators to custom type
This is done by implementing the required functions for your custom type. Sadly I could not solve this by using the regular traits like `Add`, since I can't easily check if a different trait is implemented.
This commit is contained in:
parent
fd3ec9e12d
commit
31c3827e96
14
src/main.rs
14
src/main.rs
|
@ -1,4 +1,7 @@
|
|||
use std::{any::Any, fs::read_to_string};
|
||||
use std::{
|
||||
any::Any,
|
||||
fs::read_to_string,
|
||||
};
|
||||
|
||||
use env::Env;
|
||||
use function::FunctionMap;
|
||||
|
@ -55,6 +58,14 @@ impl CustomValue for Foo {
|
|||
map.insert_native("edit_foo", Foo::edit);
|
||||
Some(map)
|
||||
}
|
||||
|
||||
fn add(&self, other: &Value) -> Value {
|
||||
if let Some(v) = other.as_t::<Foo>() {
|
||||
Foo { x: self.x + v.x }.into()
|
||||
} else {
|
||||
Value::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
@ -67,6 +78,7 @@ fn main() {
|
|||
});
|
||||
m.insert_native("waluigi", || "Waluigi");
|
||||
m.insert_native("native_test", || Foo { x: 41 });
|
||||
m.insert_native("other_foo", || Foo { x: 1 });
|
||||
|
||||
run(&m, &res);
|
||||
}
|
||||
|
|
|
@ -34,6 +34,27 @@ pub trait CustomValue: std::fmt::Debug + BoxClone {
|
|||
fn to_bool(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn add(&self, _: &Value) -> Value {
|
||||
Value::default()
|
||||
}
|
||||
|
||||
fn sub(&self, _: &Value) -> Value {
|
||||
Value::default()
|
||||
}
|
||||
|
||||
fn mul(&self, _: &Value) -> Value {
|
||||
Value::default()
|
||||
}
|
||||
|
||||
fn div(&self, _: &Value) -> Value {
|
||||
Value::default()
|
||||
}
|
||||
|
||||
fn rem(&self, _: &Value) -> Value {
|
||||
Value::default()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl PartialEq<Value> for dyn CustomValue {
|
||||
|
|
|
@ -125,6 +125,9 @@ macro_rules! math_trait {
|
|||
match (self, other) {
|
||||
(Value::Int(lhs), Value::Int(rhs)) => Value::Int(lhs.$function_name(rhs)),
|
||||
(Value::Float(lhs), Value::Float(rhs)) => Value::Float(lhs.$function_name(rhs)),
|
||||
(Value::Custom(lhs), rhs) => {
|
||||
lhs.$function_name(&rhs)
|
||||
}
|
||||
_ => Value::Error,
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue