@@ -55,8 +55,11 @@ pub struct Lua {
55
55
pub ( self ) collect_garbage : bool ,
56
56
}
57
57
58
+ /// Weak reference to Lua instance.
59
+ ///
60
+ /// This can used to prevent circular references between Lua and Rust objects.
58
61
#[ derive( Clone ) ]
59
- pub ( crate ) struct WeakLua ( XWeak < ReentrantMutex < RawLua > > ) ;
62
+ pub struct WeakLua ( XWeak < ReentrantMutex < RawLua > > ) ;
60
63
61
64
pub ( crate ) struct LuaGuard ( ArcReentrantMutexGuard < RawLua > ) ;
62
65
@@ -1995,6 +1998,15 @@ impl Lua {
1995
1998
LightUserData ( & ASYNC_POLL_PENDING as * const u8 as * mut std:: os:: raw:: c_void )
1996
1999
}
1997
2000
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
+
1998
2010
// Luau version located in `luau/mod.rs`
1999
2011
#[ cfg( not( feature = "luau" ) ) ]
2000
2012
fn disable_c_modules ( & self ) -> Result < ( ) > {
@@ -2038,11 +2050,6 @@ impl Lua {
2038
2050
LuaGuard ( self . raw . lock_arc ( ) )
2039
2051
}
2040
2052
2041
- #[ inline( always) ]
2042
- pub ( crate ) fn weak ( & self ) -> WeakLua {
2043
- WeakLua ( XRc :: downgrade ( & self . raw ) )
2044
- }
2045
-
2046
2053
/// Returns a handle to the unprotected Lua state without any synchronization.
2047
2054
///
2048
2055
/// This is useful where we know that the lock is already held by the caller.
@@ -2070,14 +2077,30 @@ impl WeakLua {
2070
2077
Some ( LuaGuard :: new ( self . 0 . upgrade ( ) ?) )
2071
2078
}
2072
2079
2080
+ /// Upgrades the weak Lua reference to a strong reference.
2081
+ ///
2082
+ /// # Panics
2083
+ ///
2084
+ /// Panics if the Lua instance is destroyed.
2073
2085
#[ track_caller]
2074
2086
#[ inline( always) ]
2075
- pub ( crate ) fn upgrade ( & self ) -> Lua {
2087
+ pub fn upgrade ( & self ) -> Lua {
2076
2088
Lua {
2077
2089
raw : self . 0 . upgrade ( ) . expect ( "Lua instance is destroyed" ) ,
2078
2090
collect_garbage : false ,
2079
2091
}
2080
2092
}
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
+ }
2081
2104
}
2082
2105
2083
2106
impl PartialEq for WeakLua {
0 commit comments