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.
main
Julius 2022-07-04 22:23:59 +02:00
parent fd3ec9e12d
commit 31c3827e96
Signed by: j00lz
GPG Key ID: AF241B0AA237BBA2
4 changed files with 45 additions and 2 deletions

View File

@ -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);
}

View File

@ -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 {

View File

@ -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,
}
}

View File

@ -32,4 +32,11 @@ if x == 0 {
print(x);
let x = 5;
print(if x < 10 { 20 } else { 30 });
print(if x < 10 { 20 } else { 30 });
let f1 = native_test();
let f2 = other_foo();
let f3 = f1 + f2;
print(f3);