Define a Callback as a Map value? #850
-
I have a function that takes a Map as additional settings, allowing the end user to customize the workload executed by the function. This workload is very flexible, and there are too many options to practically make all of them as function overloads. In the example below, this will prompt a user via a CLI for input, and we are specifying the type of prompt to use among a handful, apply case shaping, etc. It would be nice to be able to allow a user to specify a Rhai function to validate the value in the prompting. Is it possible to grab a function pointer from a Dynamic value, or am I required to always specify it in a defined method with another overload?
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I see discussion of Anonymous Functions here: https://rhai.rs/book/language/fn-anon.html?highlight=anonymous#anonymous-functions But can I get a handle to this in Rust code, and execute them in Rust? |
Beta Was this translation helpful? Give feedback.
-
Never mind. I figured it out, and it is possible and quite easy! In Rhai:
And the little prototype I put together: if let Some(validator) = settings.get("validator") {
eprintln!("Validator found!");
match validator.clone().try_cast::<FnPtr>() {
None => {}
Some(validator) => {
match validator.call_within_context::<Dynamic>(&call, (value.clone(),)) {
Ok(value) => {
if value.is_unit() {
eprintln!("We got a unit!");
} else {
eprintln!("We got: {}", value);
}
}
Err(err) => {
eprintln!("{}", err);
}
}
}
}
} |
Beta Was this translation helpful? Give feedback.
In fact, both sets of code you provided compile to the same thing, as closures are compiled behind the scene as function pointer to a defined function (with a mangled name).
You can also omit the else block because a function by default returns
()
.