rhaiscript / rhai

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

Can you use async with rhai? #215

Closed onthegit closed 4 years ago

onthegit commented 4 years ago

Can you use async/await within Rhai?

schungx commented 4 years ago

Probably not. Rhai is single-threaded, although you can build it for thread-safe environments with the sync feature.

All calls with Rhai are blocking and single-threaded.

Nevertheless, there is nothing to prevent you from using the Rhai engine in a task or something. The engine is cheap enough to spawn (if you use shared packages) so you can really spawn one per task Or you can share one among all tasks because the engine is re-entrant.

There is no API such as eval_script_asnyc such that you can execute an async script.

Is there something specific you have in mind?

onthegit commented 4 years ago

I was thinking like calling async from within rhai, not in from the rust code , concretely: is there async keyword in rhai that could be used inside the scripts that will use the native async from rust?

onthegit commented 4 years ago

async fn hello_world() { println!("hello, world!"); }

can you call this function from rhai?

schungx commented 4 years ago

Not really. async fn de-sugars to a function returning a future.

All Rhai types must be Clone. A future is not clonable. Therefore you cannot register an async function with Rhai.

And there is no await keyword in Rhai.

In fact, there is an outstanding issue that is tracking this requirement, which is to add async support to Rhai. However, it may not make it in the near future.

schungx commented 4 years ago

However, based on experience, you may not need it. I suggest that you restructure you program such that you don't need an async call within a script. Do your async stuff in Rust. Rhai is there to provide a scriptable layer over Rush code, not to replace Rust itself.

It is usually possible to revise your API such that it can be executed in a single-threaded engine. For your stored state (aka futures), you may have to wrap them in Arc.

schungx commented 4 years ago

Hi, has this issue been resolved? Can this be closed?

schungx commented 4 years ago

Closing this issue for now. If you have any more question, feel free to open another issue.