Connecting Speedy2D and Rhai with lifetimes problems

I'm trying to script speedy2d (a simple and fast graphics drawing library) with Rhai, so that the user can develop digital signage applications without having to recompile:

However, I'm caught up in trying to figure out some way to pass the short-lived &mut Graphics2D to the scripting engine. The closest I've gotten in via an Rc<RefCell<Option<Graphics2D>>, which eventually gives the kind-of "duh" error shown in the gist. However, if I use lifetimes, Rust can't gaurantee the life of the graphics put into the Rc<RefCell<...>> doesn't outlast the function. Is there a simpler approach I'm missing?

It sounds obvious, but if your Graphics2D reference is short-lived and there is no way to make it live longer (i.e. make the caller pass in an Arc<Graphics2D>), don't try to give your Rhai script access to it directly.

Instead, try to add another level of indirection... For example, your host could call into the script to queue up draw commands (e.g. enum DrawCommand { Circle { radius: f32, centre: Point }, ... }), then once the script function returns the host will execute those queued commands using its &mut Graphics2D reference.


I actually started trying that last night: creating an Rc<RefCell<Vec<GraphicsCalls>>> that holds a vec of enums that get evaluated after the script's draw() function is evaluated. I guess so long as the drawing activities are pure functions and don't themselves need to get data from the script scope, the fact that they are executed after the script has run will have the same effects. I've been trying to think of places where it could cause a break in user expectations by having the script run, then all the graphics drawing operations get applied (in order of calling).

And I think it's working! GitHub - superlou/signrs Thanks for the advice.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.