Custom state?
Is there a way to pass some custom state to a native function?
For example, I would like to run some Rune in the context of an SQL transaction. However, creating a new Rune RuntimeContext for every transaction would be quite expensive I think, so it would be better to pass the Transaction in as custom state/userdata. Then I can use this from native functions that read this custom state back.
Another use case could be a game engine where Rune code is called for every object, and a function mutates this object. For example you would call a function move(obj.x+10, obj.y) in a Rhai function update(obj) and the native function can then find the corresponding Object that you want to move.
You could also pass around the obj but this could be annoying if you are e.g. nesting things. For the SQL example this is not really feasible.
Hey,
The way right now is to pass it in as a parameter. You can even pass in references with the current system.
What you're looking to follow is probably #251.
Although I do appreciate the convenience of JavaScript for example where this is a implicit parameter. I do think it likely doesn't fit rune due to the fact it is trying to mimic Rust where even in methods self is explicit.
Changable global variables would definitely be preferred although they would need degree of protection against potential thread races if shared, especially considering I don't believe Shared is thread safe at all.
Personally I simply add a this/state parameter to start of my entry functions which solves my needs and other than needing to write it, I don't see any real differences compared with the implicit design.
Creating RuntimeContext is very rare for me unless I need them to have different module access which honestly is very rare within my projects and usually I just clone the context I have already made which is vastly cheaper and instead use different Units or simply convert Vms into SyncFunctions or Functions and reuse them which removes the need to pass around the RuntimeContext, Unit or Vm afterwards unless you really want to.