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 { fn print<T: Display>(x: T) -> String {
format!("{}", x) format!("{}", x)
} }
fn println() -> String {
"\n".to_string()
}
reg_func1!(self, "print", print, String, i32, i64, u32, u64); 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, String, f32, f64, bool, char, String);
reg_func1!(self, "print", print_debug, String, Array); 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, i32, i64, u32, u64);
reg_func1!(self, "debug", print_debug, String, f32, f64, bool, char); reg_func1!(self, "debug", print_debug, String, f32, f64, bool, char);

View File

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