#![cfg(feature = "send")] use mlua::{AnyUserData, Lua, ObjectLike, Result, UserData, UserDataMethods, UserDataRef}; use static_assertions::assert_impl_all; #[test] fn test_userdata_multithread_access_sync() -> Result<()> { let lua = Lua::new(); // This type is `Send` and `Sync`. struct MyUserData(String); assert_impl_all!(MyUserData: Send, Sync); impl UserData for MyUserData { fn add_methods>(methods: &mut M) { methods.add_method("method", |lua, this, ()| { let ud = lua.globals().get::("ud")?; assert!(ud.call_method::<()>("method2", ()).is_ok()); Ok(this.0.clone()) }); methods.add_method("method2", |_, _, ()| Ok(())); } } lua.globals().set("ud", MyUserData("hello".to_string()))?; // We acquired the shared reference. let _ud = lua.globals().get::>("ud")?; std::thread::scope(|s| { s.spawn(|| { // Getting another shared reference for `Sync` type is allowed. let _ = lua.globals().get::>("ud").unwrap(); }); }); lua.load("ud:method()").exec().unwrap(); Ok(()) }