Skip to content

Commit c1a018a

Browse files
committed
Add AnyUserData::type_id method
1 parent 4d2ff45 commit c1a018a

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/userdata.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -623,10 +623,9 @@ impl AnyUserData {
623623
/// Checks whether the type of this userdata is `T`.
624624
#[inline]
625625
pub fn is<T: 'static>(&self) -> bool {
626-
let lua = self.0.lua.lock();
627-
let type_id = lua.get_userdata_ref_type_id(&self.0);
626+
let type_id = self.type_id();
628627
// We do not use wrapped types here, rather prefer to check the "real" type of the userdata
629-
matches!(type_id, Ok(Some(type_id)) if type_id == TypeId::of::<T>())
628+
matches!(type_id, Some(type_id) if type_id == TypeId::of::<T>())
630629
}
631630

632631
/// Borrow this userdata immutably if it is of type `T`.
@@ -918,6 +917,15 @@ impl AnyUserData {
918917
self.0.to_pointer()
919918
}
920919

920+
/// Returns [`TypeId`] of this userdata if it is registered and `'static`.
921+
///
922+
/// This method is not available for scoped userdata.
923+
#[inline]
924+
pub fn type_id(&self) -> Option<TypeId> {
925+
let lua = self.0.lua.lock();
926+
lua.get_userdata_ref_type_id(&self.0).ok().flatten()
927+
}
928+
921929
/// Returns a type name of this `UserData` (from a metatable field).
922930
pub(crate) fn type_name(&self) -> Result<Option<StdString>> {
923931
let lua = self.0.lua.lock();

tests/userdata.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::any::TypeId;
12
use std::collections::HashMap;
23
use std::string::String as StdString;
34
use std::sync::Arc;
@@ -23,9 +24,11 @@ fn test_userdata() -> Result<()> {
2324
let userdata2 = lua.create_userdata(UserData2(Box::new(2)))?;
2425

2526
assert!(userdata1.is::<UserData1>());
27+
assert!(userdata1.type_id() == Some(TypeId::of::<UserData1>()));
2628
assert!(!userdata1.is::<UserData2>());
2729
assert!(userdata2.is::<UserData2>());
2830
assert!(!userdata2.is::<UserData1>());
31+
assert!(userdata2.type_id() == Some(TypeId::of::<UserData2>()));
2932

3033
assert_eq!(userdata1.borrow::<UserData1>()?.0, 1);
3134
assert_eq!(*userdata2.borrow::<UserData2>()?.0, 2);

0 commit comments

Comments
 (0)