@@ -55,8 +55,11 @@ pub struct Lua {
5555 pub ( self ) collect_garbage : bool ,
5656}
5757
58+ /// Weak reference to Lua instance.
59+ ///
60+ /// This can used to prevent circular references between Lua and Rust objects.
5861#[ derive( Clone ) ]
59- pub ( crate ) struct WeakLua ( XWeak < ReentrantMutex < RawLua > > ) ;
62+ pub struct WeakLua ( XWeak < ReentrantMutex < RawLua > > ) ;
6063
6164pub ( crate ) struct LuaGuard ( ArcReentrantMutexGuard < RawLua > ) ;
6265
@@ -1995,6 +1998,15 @@ impl Lua {
19951998 LightUserData ( & ASYNC_POLL_PENDING as * const u8 as * mut std:: os:: raw:: c_void )
19961999 }
19972000
2001+ /// Returns a weak reference to the Lua instance.
2002+ ///
2003+ /// This is useful for creating a reference to the Lua instance that does not prevent it from
2004+ /// being deallocated.
2005+ #[ inline( always) ]
2006+ pub fn weak ( & self ) -> WeakLua {
2007+ WeakLua ( XRc :: downgrade ( & self . raw ) )
2008+ }
2009+
19982010 // Luau version located in `luau/mod.rs`
19992011 #[ cfg( not( feature = "luau" ) ) ]
20002012 fn disable_c_modules ( & self ) -> Result < ( ) > {
@@ -2038,11 +2050,6 @@ impl Lua {
20382050 LuaGuard ( self . raw . lock_arc ( ) )
20392051 }
20402052
2041- #[ inline( always) ]
2042- pub ( crate ) fn weak ( & self ) -> WeakLua {
2043- WeakLua ( XRc :: downgrade ( & self . raw ) )
2044- }
2045-
20462053 /// Returns a handle to the unprotected Lua state without any synchronization.
20472054 ///
20482055 /// This is useful where we know that the lock is already held by the caller.
@@ -2070,14 +2077,30 @@ impl WeakLua {
20702077 Some ( LuaGuard :: new ( self . 0 . upgrade ( ) ?) )
20712078 }
20722079
2080+ /// Upgrades the weak Lua reference to a strong reference.
2081+ ///
2082+ /// # Panics
2083+ ///
2084+ /// Panics if the Lua instance is destroyed.
20732085 #[ track_caller]
20742086 #[ inline( always) ]
2075- pub ( crate ) fn upgrade ( & self ) -> Lua {
2087+ pub fn upgrade ( & self ) -> Lua {
20762088 Lua {
20772089 raw : self . 0 . upgrade ( ) . expect ( "Lua instance is destroyed" ) ,
20782090 collect_garbage : false ,
20792091 }
20802092 }
2093+
2094+ /// Tries to upgrade the weak Lua reference to a strong reference.
2095+ ///
2096+ /// Returns `None` if the Lua instance is destroyed.
2097+ #[ inline( always) ]
2098+ pub fn try_upgrade ( & self ) -> Option < Lua > {
2099+ Some ( Lua {
2100+ raw : self . 0 . upgrade ( ) ?,
2101+ collect_garbage : false ,
2102+ } )
2103+ }
20812104}
20822105
20832106impl PartialEq for WeakLua {
0 commit comments