[][src]Type Definition lox_lang::NativeFun

type NativeFun = Box<dyn FnMut(&[Value]) -> Result<Value, Box<dyn Error>>>;

A natively-implemented function that can be called from Lox code.

Example

/// This function wraps `str::replace` for use in Lox
let replace = vm.alloc(Box::new(|args: &[Value]| {
    match args {
        [Value::r#String(text), Value::r#String(pat), Value::r#String(rep)] =>
            Ok(text.replace(pat.as_ref(), rep.as_ref()).into()),
        _ => Err(Box::new(MyError) as Box<dyn Error>),
    }
}) as lox_lang::NativeFun);

vm.define_global("replace", Value::NativeFun(replace));

vm.interpret(r#"
    var proverb = "what is old becomes new again";
    print replace(proverb, "new", "old");
"#);

assert_eq!(output, "what is old becomes old again\n");