rhaiscript / rhai

Rhai - An embedded scripting language for Rust.
https://crates.io/crates/rhai
Apache License 2.0
3.73k stars 175 forks source link

Documentation for Option #538

Closed njust closed 2 years ago

njust commented 2 years ago

I was searching the rhai.rs/book how to handle optional parameters, but couldn't find something helpful. Should I implement my own option based on the enum documentation ?

schungx commented 2 years ago

Depends on whether your function is Rust-native or Rhai-based.

For Rhai functions: All parameters are dynamic, so just pass () as None. Or: leverage overloading (see below).

fn foo(x, y, z) {
    if z == () { z = ""; }
    ...
}
fn foo(x, y) { foo(x, y, ()) }

For Rust functions: Leverage overloading by registering multiple versions of the same function, some without optional parameters.

pub fn foo(x: INT, y: bool, z: &str) { ... }

#[rhai_fn(name = "foo")]
pub fn foo2(x: INT, y: bool) {  foo(x, y, "") }

#[rhai_fn(name = "foo")]
pub fn foo3(x: INT) { foo2(x, true) }
njust commented 2 years ago

Thanks a lot. The relevant page from the online book is here, in case someone else stumbles upon this.