mlua icon indicating copy to clipboard operation
mlua copied to clipboard

Remove 'lua lifetimes

Open alphaqu opened this issue 2 years ago • 4 comments

The code is just a proof of concept, this really should not be merged because of panic! usage.

Hi there! This pull-request shows off how lifetimes might get removed from the api. In small use cases mlua is really useful but for games like rustaria which i am developing together with some other people, it makes this library unusable.

Most of the lifetimes have been replaced by the LuaWeakRef struct which takes a Weak reference of the Lua internals. If the context gets dropped the object will either return Err(Error::LuaUnavailable) or panic (which is not ideal, many returns need to return result now). I would like to have your input on this, as I think this is a great start on making mlua integrable in huge systems.

alphaqu avatar Apr 16 '22 16:04 alphaqu

Thanks! I agree that 'lua lifetime makes many things quite complex. I've been thinking about removing it and have non-published implementation of about the same. Also thinking about making Lua Sync by protecting access to VM internals using ReentrantMutex. This is the main blocker for 1.0.

Out of curiosity, have you consider making 'lua lifetime as 'static, effectively removing some pain?

let lua = Lua::new().into_static();

Panic when Lua instance dropped should not be a big issue. This is a logic error I believe (similar to panic when accessing array by non-valid index, etc).

khvzak avatar Apr 16 '22 22:04 khvzak

Hi there, Its not possible for us to make Lua static as we use lua for our API and every plugin has their own lua context. This makes static impractical as a plugin might get unloaded at runtime because of a critical failiure.

alphaqu avatar Apr 17 '22 09:04 alphaqu

Any update on this? The lifetime makes everything terrible to use and into_static() is hidden from docs, and discouraged 🙂

Kampfkarren avatar Sep 15 '22 01:09 Kampfkarren

I'd love to see this change, but the main concern is performance implications. To untie Value from 'lua lifetime we need to keep Weak reference to Lua inside. Then every time check that number of strong references is more than zero when working with it. Generally this is fine, but situation get worse with send feature flag enabled. It's unsafe to move any Value to another thread and call methods on it. To protect the Lua VM from concurrent access to their memory we need to wrap every Weak reference to a ReentrantMutex and it's slow.

Probably making a hybrid design and add Value: 'static (with Mutex) and ValueRef<'lua> (without Mutex) would be a better alternative.

khvzak avatar Sep 16 '22 10:09 khvzak

I believe the upcoming "owned" types in mlua v0.9 should be a good solution. v0.9-rc.1 is almost ready for release

OwnedTable OwnedFunction OwnedAnyUserData OwnedString

khvzak avatar Jul 09 '23 22:07 khvzak