Skip to content

How do I checkpoint and resume Rhai evaluation? #769

Description

@vi

I want something like this

use rhai::{Engine, EvalAltResult, Position};

struct MyContext {
    e: Engine,
}

impl MyContext {
    fn new() -> MyContext {
        let mut e = Engine::new();
        fn suspend() -> Result<i32, Box<EvalAltResult>> {
            let resumed = true; // ?
            if resumed {
                Ok(3 /* assuming getting from some channel */)
            } else {
                // How to I save execution context to be able to return twice?
                Err(Box::new(EvalAltResult::ErrorTerminated(().into(), Position::NONE)))
            }
        }
        
        e.register_fn("suspend", suspend);
        MyContext { e }
    }
    fn start(&self) {
        let _ = self.e.eval::<()>(r#"
            print(1);
            print(suspend());
            print(4);
        "#);
    }
    fn resume(&self, _x: i32) {
        // (Assuming sending _x to the channel)
        
        // ?
    }
}

fn main()
{
    let state = MyContext::new();
    state.start();
    // Rhai evaluation stack frames should not be absent. It should be in inert, "frozen" state.
    // N suspended evaluations should not occupy N operation system threads.
    println!("2");
    state.resume(3);
}

It should print 1\n2\n3\n4\n.

Is there some example (e.g. using internals feature) to attain this?

Alternatively, is there something like "call with current continuation" in Rhai, to avoid each suspension point becoming a closure in Rhai code (i.e. callback hell)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions