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

register a function in rhai that uses/binds a variable from rust #523

Closed RudolfVonKrugstein closed 2 years ago

RudolfVonKrugstein commented 2 years ago

I am very new to rust, so maybe this is just me being a newbie.

I want to do something like this:

fn get(url: &str) {
    // Some code to send a http GET to the given url
}

fn build_engine() {
    let target_url = load_url_from_config();
    let mut engine = rhai::Engine::new();
    engine.register_fn("get_target_url", || get(target_url));
}

But it seems, that I cannot pass closures to register_fn:

the trait `RegisterNativeFunction<_, ()>` is not implemented for ...

But how can I get the variable "target_url" into the call if get_targer_url (rhai function) whithout having to pass it in rhai?

cn-kali-team commented 2 years ago

https://rhai.rs/book/rust/functions.html

schungx commented 2 years ago

You'll need to give more info, such as what is the return type of get... is it Clone? Rhai needs to work with data types that are Clone, for example.

Also, functions for register_fn must be 'static, so maybe you need to do: move || get(target_url)

schungx commented 2 years ago

Closing this for now. Feel free to reopen if you have any problems.