Skip to content

Commit 62f0bb9

Browse files
committed
Add Lua::create_ser_any_userdata() function
1 parent f67f864 commit 62f0bb9

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/lua.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1746,6 +1746,21 @@ impl Lua {
17461746
unsafe { self.make_any_userdata(UserDataCell::new(data)) }
17471747
}
17481748

1749+
/// Creates a Lua userdata object from a custom serializable Rust type.
1750+
///
1751+
/// See [`Lua::create_any_userdata()`] for more details.
1752+
///
1753+
/// Requires `feature = "serialize"`
1754+
#[cfg(feature = "serialize")]
1755+
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
1756+
#[inline]
1757+
pub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData>
1758+
where
1759+
T: Serialize + MaybeSend + 'static,
1760+
{
1761+
unsafe { self.make_any_userdata(UserDataCell::new_ser(data)) }
1762+
}
1763+
17491764
/// Registers a custom Rust type in Lua to use in userdata objects.
17501765
///
17511766
/// This methods provides a way to add fields or methods to userdata objects of a type `T`.

tests/serde.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,21 @@ fn test_serialize_in_scope() -> LuaResult<()> {
115115
Ok(())
116116
}
117117

118+
#[test]
119+
fn test_serialize_any_userdata() -> Result<(), Box<dyn StdError>> {
120+
let lua = Lua::new();
121+
122+
let json_val = serde_json::json!({
123+
"a": 1,
124+
"b": "test",
125+
});
126+
let json_ud = lua.create_ser_any_userdata(json_val)?;
127+
let json_str = serde_json::to_string_pretty(&json_ud)?;
128+
assert_eq!(json_str, "{\n \"a\": 1,\n \"b\": \"test\"\n}");
129+
130+
Ok(())
131+
}
132+
118133
#[test]
119134
fn test_serialize_failure() -> Result<(), Box<dyn StdError>> {
120135
#[derive(Serialize)]

0 commit comments

Comments
 (0)