Allow script functions to override built-in functions.

This commit is contained in:
Stephen Chung 2020-03-02 15:19:41 +08:00
parent a5e09295f8
commit adaa65f953
2 changed files with 9 additions and 23 deletions

View File

@ -195,14 +195,12 @@ impl Engine {
fn print<T: Display>(x: T) -> String {
format!("{}", x)
}
fn println() -> String {
"\n".to_string()
}
reg_func1!(self, "print", print, String, i32, i64, u32, u64);
reg_func1!(self, "print", print, String, f32, f64, bool, char, String);
reg_func1!(self, "print", print_debug, String, Array);
self.register_fn("print", println);
self.register_fn("print", || "".to_string());
self.register_fn("print", |_: ()| "".to_string());
reg_func1!(self, "debug", print_debug, String, i32, i64, u32, u64);
reg_func1!(self, "debug", print_debug, String, f32, f64, bool, char);

View File

@ -244,28 +244,16 @@ impl Engine {
.collect::<Vec<_>>()
);
let spec = FnSpec {
let mut spec = FnSpec {
ident: ident.clone(),
args: Some(args.iter().map(|a| Any::type_id(&**a)).collect()),
args: None,
};
// First search in script-defined functions (can override built-in),
// then in built-in's, then retry again with no arguments
let fn_def = self
.script_fns
.get(&spec)
.or_else(|| self.fns.get(&spec))
.or_else(|| {
self.script_fns.get(&FnSpec {
ident: ident.clone(),
args: None,
})
})
.or_else(|| {
self.fns.get(&FnSpec {
ident: ident.clone(),
args: None,
})
// then in built-in's
let fn_def = self.script_fns.get(&spec).or_else(|| {
spec.args = Some(args.iter().map(|a| Any::type_id(&**a)).collect());
self.fns.get(&spec)
});
if let Some(f) = fn_def {