mirror of
https://github.com/mlua-rs/mlua
synced 2026-06-08 16:05:43 +00:00
Add Lua::create_ser_any_userdata() function
This commit is contained in:
+15
@@ -1746,6 +1746,21 @@ impl Lua {
|
||||
unsafe { self.make_any_userdata(UserDataCell::new(data)) }
|
||||
}
|
||||
|
||||
/// Creates a Lua userdata object from a custom serializable Rust type.
|
||||
///
|
||||
/// See [`Lua::create_any_userdata()`] for more details.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
#[inline]
|
||||
pub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData>
|
||||
where
|
||||
T: Serialize + MaybeSend + 'static,
|
||||
{
|
||||
unsafe { self.make_any_userdata(UserDataCell::new_ser(data)) }
|
||||
}
|
||||
|
||||
/// Registers a custom Rust type in Lua to use in userdata objects.
|
||||
///
|
||||
/// This methods provides a way to add fields or methods to userdata objects of a type `T`.
|
||||
|
||||
@@ -115,6 +115,21 @@ fn test_serialize_in_scope() -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_any_userdata() -> Result<(), Box<dyn StdError>> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let json_val = serde_json::json!({
|
||||
"a": 1,
|
||||
"b": "test",
|
||||
});
|
||||
let json_ud = lua.create_ser_any_userdata(json_val)?;
|
||||
let json_str = serde_json::to_string_pretty(&json_ud)?;
|
||||
assert_eq!(json_str, "{\n \"a\": 1,\n \"b\": \"test\"\n}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_failure() -> Result<(), Box<dyn StdError>> {
|
||||
#[derive(Serialize)]
|
||||
|
||||
Reference in New Issue
Block a user