Alternative to pattern which would need double mutable borrow? #217
-
I'm trying to emulate a pattern I've seen in a few different game engines, all in C++. The premise is that something happens during a mutating operation in Rust code that triggers a mutating callback in Lua. The corresponding Rust code, simplified, would look like this: let lua = Lua::new();
let mutating_lua_func = lua.create_function(|_, _| {
// _Absolutely must_ be able to modify anything in `game_state`
Ok(())
});
lua.globals().set("mutating_func", mutating_lua_func);
for thing in game_state.characters() {
let need_script_call = thing.mutate(); // Rust function
if need_script_call {
lua.globals().get("mutating_func").call();
}
} I can't see any way of allowing this without borrowing Is this just something that Rust will not allow? Is there an entirely other way I could be structuring this to fix all of this? I know it's a reasonable use case; if I want, for example, enemy damage code to happen in Rust while a script responds to that damage by calling into random number generators, modifying level geometry, modifying the rest of the ECS, et cetera, I at least need something similar. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
What is inside Or maybe you can iterate over indicies of elements and then mutably borrow for i in 0..n {
let mut thing = &mut game_state.characters()[i];
let need_script_call = thing.mutate();
drop(thing);
if need_script_call {
lua.globals().get("mutating_func").call();
}
} If the code runs in a single thread also |
Beta Was this translation helpful? Give feedback.
-
I think I figured out what I needed:
I'm not sure I would have thought of this if I wasn't considering the answer you gave. Thanks for your time and consideration. |
Beta Was this translation helpful? Give feedback.
I think I figured out what I needed:
Arc<Mutex<>>
.Vec
.It's not ideal performance-wise - I was hoping to be able to avoid running a lock for every native call in what could potentially be thousands of native scripts, and I'd prefer not to have to do so much iterator-collecting - but parking_lot'…