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

Question about execution pause #768

Open diamantisk opened 1 year ago

diamantisk commented 1 year ago

Is there any way or workaround to pause the execution, store context and resume the execution and context from that point?

emesare commented 1 year ago

Yes, I think what you want is the Debugging Interface (enabled through the flag debugging).

schungx commented 1 year ago

Is there any way or workaround to pause the execution, store context and resume the execution and context from that point?

Not exactly what you like to do. You have just described async, which Rhai is not.

However, as @emesare mentioned, you can use the debugging interface or use the on_progress callback. The pitfalls is that you usually need to use a dedicated thread to stop the execution and another thread to control it.

diamantisk commented 1 year ago

Thank you for pointing this out; I will certainly experiment with this idea. I envision a method where a host function, defined in Rust, is called by Rhai. This function would have the capability to suspend or yield the execution of Rhai at that specific point. After pausing and securely storing the context, an asynchronous task would be executed on the Rust side. Upon completion of this task, Rust would restore the previously stored context, allowing the Rhai script to resume execution seamlessly.

schungx commented 1 year ago

You can probably do that easily by encapsulating a channel inside on_progress. Use a dedicated thread to run the engine, and use messages to control whether on_progress stalls, waiting for the resume command. There is no need to use the debugging interface if you just want simple start/stop. There is also no need to store any context, as the thread acts as the context.

schungx commented 12 months ago

I have coded up an example: https://github.com/schungx/rhai/blob/master/examples/pause_and_resume.rs

schungx commented 12 months ago

I envision a method where a host function, defined in Rust, is called by Rhai

If you want such a suspend function, it is extremely simple to register one. Simply move in a pair of channels. When called, send a message to the tx channel, and wait for a reply from the rx channel. In the meantime, the thread suspends waiting for the channel message, which is exactly what you want to achieve.