1use std::any::TypeId;
26use std::cell::RefCell;
27use std::marker::PhantomData;
28
29use crate::callback::{create_callback_function, BoxedCallback};
30use crate::error::{Error, Result};
31use crate::function::Function;
32use crate::state::{Lua, LuaRef};
33use crate::sync::{MaybeSend, MaybeSync, NotSync, XRc, NOT_SYNC};
34use crate::sys::*;
35use crate::table::Table;
36use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
37use crate::value::Value;
38
39pub trait UserData: Sized {
44 fn add_fields<F: UserDataFields<Self>>(_fields: &mut F) {}
46
47 fn add_methods<M: UserDataMethods<Self>>(_methods: &mut M) {}
49}
50
51pub trait UserDataMethods<T> {
55 fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
57 where
58 M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
59 A: FromLuaMulti,
60 R: IntoLuaMulti;
61
62 fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
64 where
65 M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
66 A: FromLuaMulti,
67 R: IntoLuaMulti;
68
69 fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
71 where
72 F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
73 A: FromLuaMulti,
74 R: IntoLuaMulti;
75
76 fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
79 where
80 M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
81 A: FromLuaMulti,
82 R: IntoLuaMulti;
83
84 fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
86 where
87 M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
88 A: FromLuaMulti,
89 R: IntoLuaMulti;
90}
91
92pub trait UserDataFields<T> {
97 fn add_field<V>(&mut self, name: impl Into<String>, value: V)
99 where
100 V: IntoLua + Clone + MaybeSend + 'static;
101
102 fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
104 where
105 M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
106 R: IntoLua;
107
108 fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
110 where
111 M: Fn(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
112 A: FromLua;
113
114 fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
116 where
117 F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
118 R: IntoLua;
119
120 fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
123 where
124 F: Fn(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
125 A: FromLua;
126}
127
128#[derive(Clone)]
135pub struct AnyUserData {
136 pub(crate) reference: XRc<LuaRef>,
137 pub(crate) _not_sync: NotSync,
138}
139
140impl AnyUserData {
141 pub(crate) fn from_ref(reference: LuaRef) -> AnyUserData {
142 AnyUserData {
143 reference: XRc::new(reference),
144 _not_sync: NOT_SYNC,
145 }
146 }
147
148 pub(crate) unsafe fn push_to_stack(&self) {
149 self.reference.push();
150 }
151
152 pub fn lua(&self) -> Lua {
154 self.reference.lua()
155 }
156
157 pub fn to_pointer(&self) -> *const c_void {
160 let state = self.reference.state();
161 unsafe {
162 self.reference.push();
163 let p = lua_topointer(state, -1);
164 lua_pop(state, 1);
165 p
166 }
167 }
168
169 pub fn equals(&self, other: &AnyUserData) -> Result<bool> {
172 let lua = self.lua();
173 let state = lua.state();
174 unsafe {
175 self.reference.push();
176 other.reference.push();
177 let eq = lua_equal(state, -2, -1);
178 lua_pop(state, 2);
179 Ok(eq != 0)
180 }
181 }
182
183 fn cell<T: 'static>(&self) -> Result<&UserDataCell<T>> {
187 let state = self.reference.state();
188 unsafe {
189 self.reference.push();
190 let ptr = lua_touserdata(state, -1);
191 lua_pop(state, 1);
192 if ptr.is_null() {
193 return Err(Error::UserDataTypeMismatch);
194 }
195 let header = &*(ptr as *const UserDataHeader);
197 if header.type_id != TypeId::of::<T>() {
198 return Err(Error::UserDataTypeMismatch);
199 }
200 Ok(&*(ptr as *const UserDataCell<T>))
201 }
202 }
203
204 pub fn is<T: 'static>(&self) -> bool {
207 match self.cell::<T>() {
208 Ok(cell) => cell.cell.borrow().is_some(),
209 Err(_) => false,
210 }
211 }
212
213 pub fn type_id(&self) -> Option<TypeId> {
217 let state = self.reference.state();
218 unsafe {
219 self.reference.push();
220 let ptr = lua_touserdata(state, -1);
221 lua_pop(state, 1);
222 if ptr.is_null() {
223 return None;
224 }
225 let header = &*(ptr as *const UserDataHeader);
228 Some(header.type_id)
229 }
230 }
231
232 pub fn borrow<T: 'static>(&self) -> Result<UserDataRef<'_, T>> {
237 let cell = self.cell::<T>()?;
238 let guard = cell
239 .cell
240 .try_borrow()
241 .map_err(|_| Error::UserDataBorrowError)?;
242 if guard.is_none() {
243 return Err(Error::UserDataDestructed);
244 }
245 Ok(UserDataRef {
246 guard,
247 _marker: PhantomData,
248 })
249 }
250
251 pub fn borrow_mut<T: 'static>(&self) -> Result<UserDataRefMut<'_, T>> {
254 let cell = self.cell::<T>()?;
255 let guard = cell
256 .cell
257 .try_borrow_mut()
258 .map_err(|_| Error::UserDataBorrowMutError)?;
259 if guard.is_none() {
260 return Err(Error::UserDataDestructed);
261 }
262 Ok(UserDataRefMut {
263 guard,
264 _marker: PhantomData,
265 })
266 }
267
268 pub fn take<T: 'static>(&self) -> Result<T> {
273 let cell = self.cell::<T>()?;
274 let mut guard = cell
275 .cell
276 .try_borrow_mut()
277 .map_err(|_| Error::UserDataBorrowMutError)?;
278 guard.take().ok_or(Error::UserDataDestructed)
279 }
280}
281
282pub struct UserDataRef<'a, T> {
285 guard: std::cell::Ref<'a, Option<T>>,
286 _marker: PhantomData<T>,
287}
288
289impl<T> std::ops::Deref for UserDataRef<'_, T> {
290 type Target = T;
291 fn deref(&self) -> &T {
292 self.guard.as_ref().expect("userdata destructed")
294 }
295}
296
297impl<T: std::fmt::Debug> std::fmt::Debug for UserDataRef<'_, T> {
298 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299 std::fmt::Debug::fmt(&**self, f)
300 }
301}
302
303impl<T: std::fmt::Display> std::fmt::Display for UserDataRef<'_, T> {
304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305 std::fmt::Display::fmt(&**self, f)
306 }
307}
308
309pub struct UserDataRefMut<'a, T> {
312 guard: std::cell::RefMut<'a, Option<T>>,
313 _marker: PhantomData<T>,
314}
315
316impl<T> std::ops::Deref for UserDataRefMut<'_, T> {
317 type Target = T;
318 fn deref(&self) -> &T {
319 self.guard.as_ref().expect("userdata destructed")
320 }
321}
322
323impl<T> std::ops::DerefMut for UserDataRefMut<'_, T> {
324 fn deref_mut(&mut self) -> &mut T {
325 self.guard.as_mut().expect("userdata destructed")
326 }
327}
328
329impl<T: std::fmt::Debug> std::fmt::Debug for UserDataRefMut<'_, T> {
330 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331 std::fmt::Debug::fmt(&**self, f)
332 }
333}
334
335impl<T: std::fmt::Display> std::fmt::Display for UserDataRefMut<'_, T> {
336 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337 std::fmt::Display::fmt(&**self, f)
338 }
339}
340
341impl std::fmt::Debug for AnyUserData {
342 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343 write!(f, "UserData")
344 }
345}
346
347impl PartialEq for AnyUserData {
348 fn eq(&self, other: &Self) -> bool {
349 self.to_pointer() == other.to_pointer()
351 }
352}
353
354impl<T: UserData + crate::sync::MaybeSend + crate::sync::MaybeSync + 'static> IntoLua for T {
361 fn into_lua(self, lua: &Lua) -> Result<Value> {
362 Ok(Value::UserData(lua.create_userdata(self)?))
363 }
364}
365
366impl IntoLua for AnyUserData {
367 fn into_lua(self, _lua: &Lua) -> Result<Value> {
368 Ok(Value::UserData(self))
369 }
370}
371
372impl IntoLua for &AnyUserData {
373 fn into_lua(self, _lua: &Lua) -> Result<Value> {
374 Ok(Value::UserData(self.clone()))
375 }
376}
377
378impl FromLua for AnyUserData {
379 fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
380 match value {
381 Value::UserData(ud) => Ok(ud),
382 other => Err(Error::FromLuaConversionError {
383 from: other.type_name(),
384 to: "AnyUserData".to_string(),
385 message: None,
386 }),
387 }
388 }
389}
390
391#[repr(C)]
400struct UserDataHeader {
401 type_id: TypeId,
402}
403
404#[repr(C)]
406struct UserDataCell<T> {
407 type_id: TypeId,
408 cell: RefCell<Option<T>>,
409}
410
411fn recover_cell<'a, T: 'static>(lua: &Lua, value: &Value) -> Result<&'a UserDataCell<T>> {
413 match value {
414 Value::UserData(ud) => {
415 let state = lua.state();
416 unsafe {
417 ud.reference.push();
418 let ptr = lua_touserdata(state, -1);
419 lua_pop(state, 1);
420 if ptr.is_null() {
421 return Err(Error::UserDataTypeMismatch);
422 }
423 let header = &*(ptr as *const UserDataHeader);
424 if header.type_id != TypeId::of::<T>() {
425 return Err(Error::UserDataTypeMismatch);
426 }
427 Ok(&*(ptr as *const UserDataCell<T>))
428 }
429 }
430 _ => Err(Error::UserDataTypeMismatch),
431 }
432}
433
434struct Registered {
441 name: String,
442 is_meta: bool,
443 callback: BoxedCallback,
444}
445
446struct FieldEntry {
448 name: String,
449 is_get: bool,
451 callback: BoxedCallback,
452}
453
454struct Collector<T> {
457 methods: Vec<Registered>,
458 fields: Vec<FieldEntry>,
459 _phantom: PhantomData<T>,
460}
461
462impl<T> Collector<T> {
463 fn new() -> Self {
464 Collector {
465 methods: Vec::new(),
466 fields: Vec::new(),
467 _phantom: PhantomData,
468 }
469 }
470}
471
472impl<T: 'static> UserDataMethods<T> for Collector<T> {
473 fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
474 where
475 M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
476 A: FromLuaMulti,
477 R: IntoLuaMulti,
478 {
479 let callback: BoxedCallback = Box::new(move |lua, mut args| {
480 let this = args.pop_front().unwrap_or(Value::Nil);
481 let cell = recover_cell::<T>(lua, &this)?;
482 let a = A::from_lua_multi(args, lua)?;
483 let borrowed = cell
484 .cell
485 .try_borrow()
486 .map_err(|_| Error::UserDataBorrowError)?;
487 let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
488 let r = method(lua, data, a)?;
489 r.into_lua_multi(lua)
490 });
491 self.methods.push(Registered {
492 name: name.into(),
493 is_meta: false,
494 callback,
495 });
496 }
497
498 fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
499 where
500 M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
501 A: FromLuaMulti,
502 R: IntoLuaMulti,
503 {
504 let callback: BoxedCallback = Box::new(move |lua, mut args| {
505 let this = args.pop_front().unwrap_or(Value::Nil);
506 let cell = recover_cell::<T>(lua, &this)?;
507 let a = A::from_lua_multi(args, lua)?;
508 let mut borrowed = cell
509 .cell
510 .try_borrow_mut()
511 .map_err(|_| Error::UserDataBorrowMutError)?;
512 let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
513 let r = method(lua, data, a)?;
514 r.into_lua_multi(lua)
515 });
516 self.methods.push(Registered {
517 name: name.into(),
518 is_meta: false,
519 callback,
520 });
521 }
522
523 fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
524 where
525 F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
526 A: FromLuaMulti,
527 R: IntoLuaMulti,
528 {
529 let callback: BoxedCallback = Box::new(move |lua, args| {
530 let a = A::from_lua_multi(args, lua)?;
531 let r = function(lua, a)?;
532 r.into_lua_multi(lua)
533 });
534 self.methods.push(Registered {
535 name: name.into(),
536 is_meta: false,
537 callback,
538 });
539 }
540
541 fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
542 where
543 M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
544 A: FromLuaMulti,
545 R: IntoLuaMulti,
546 {
547 let callback: BoxedCallback = Box::new(move |lua, mut args| {
548 let this = args.pop_front().unwrap_or(Value::Nil);
549 let cell = recover_cell::<T>(lua, &this)?;
550 let a = A::from_lua_multi(args, lua)?;
551 let borrowed = cell
552 .cell
553 .try_borrow()
554 .map_err(|_| Error::UserDataBorrowError)?;
555 let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
556 let r = method(lua, data, a)?;
557 r.into_lua_multi(lua)
558 });
559 self.methods.push(Registered {
560 name: name.into(),
561 is_meta: true,
562 callback,
563 });
564 }
565
566 fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
567 where
568 M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
569 A: FromLuaMulti,
570 R: IntoLuaMulti,
571 {
572 let callback: BoxedCallback = Box::new(move |lua, mut args| {
573 let this = args.pop_front().unwrap_or(Value::Nil);
574 let cell = recover_cell::<T>(lua, &this)?;
575 let a = A::from_lua_multi(args, lua)?;
576 let mut borrowed = cell
577 .cell
578 .try_borrow_mut()
579 .map_err(|_| Error::UserDataBorrowMutError)?;
580 let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
581 let r = method(lua, data, a)?;
582 r.into_lua_multi(lua)
583 });
584 self.methods.push(Registered {
585 name: name.into(),
586 is_meta: true,
587 callback,
588 });
589 }
590}
591
592impl<T: 'static> UserDataFields<T> for Collector<T> {
593 fn add_field<V>(&mut self, name: impl Into<String>, value: V)
594 where
595 V: IntoLua + Clone + MaybeSend + 'static,
596 {
597 let callback: BoxedCallback = Box::new(move |lua, _args| {
598 let v = value.clone().into_lua(lua)?;
599 v.into_lua_multi(lua)
600 });
601 self.fields.push(FieldEntry {
602 name: name.into(),
603 is_get: true,
604 callback,
605 });
606 }
607
608 fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
609 where
610 M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
611 R: IntoLua,
612 {
613 let callback: BoxedCallback = Box::new(move |lua, mut args| {
614 let this = args.pop_front().unwrap_or(Value::Nil);
615 let cell = recover_cell::<T>(lua, &this)?;
616 let borrowed = cell
617 .cell
618 .try_borrow()
619 .map_err(|_| Error::UserDataBorrowError)?;
620 let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
621 let r = method(lua, data)?;
622 r.into_lua_multi(lua)
623 });
624 self.fields.push(FieldEntry {
625 name: name.into(),
626 is_get: true,
627 callback,
628 });
629 }
630
631 fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
632 where
633 M: Fn(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
634 A: FromLua,
635 {
636 let callback: BoxedCallback = Box::new(move |lua, mut args| {
637 let this = args.pop_front().unwrap_or(Value::Nil);
638 let cell = recover_cell::<T>(lua, &this)?;
639 let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
640 let mut borrowed = cell
641 .cell
642 .try_borrow_mut()
643 .map_err(|_| Error::UserDataBorrowMutError)?;
644 let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
645 method(lua, data, val)?;
646 ().into_lua_multi(lua)
647 });
648 self.fields.push(FieldEntry {
649 name: name.into(),
650 is_get: false,
651 callback,
652 });
653 }
654
655 fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
656 where
657 F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
658 R: IntoLua,
659 {
660 let callback: BoxedCallback = Box::new(move |lua, mut args| {
661 let this = args.pop_front().unwrap_or(Value::Nil);
662 let ud = AnyUserData::from_lua(this, lua)?;
663 let r = function(lua, ud)?;
664 r.into_lua_multi(lua)
665 });
666 self.fields.push(FieldEntry {
667 name: name.into(),
668 is_get: true,
669 callback,
670 });
671 }
672
673 fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
674 where
675 F: Fn(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
676 A: FromLua,
677 {
678 let callback: BoxedCallback = Box::new(move |lua, mut args| {
679 let this = args.pop_front().unwrap_or(Value::Nil);
680 let ud = AnyUserData::from_lua(this, lua)?;
681 let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
682 function(lua, ud, val)?;
683 ().into_lua_multi(lua)
684 });
685 self.fields.push(FieldEntry {
686 name: name.into(),
687 is_get: false,
688 callback,
689 });
690 }
691}
692
693unsafe extern "C" fn userdata_dtor<T>(ptr: *mut c_void) {
695 if !ptr.is_null() {
696 unsafe { core::ptr::drop_in_place(ptr as *mut UserDataCell<T>) };
697 }
698}
699
700use std::sync::atomic::{AtomicU64, Ordering};
723
724static SCOPED_MARKER: AtomicU64 = AtomicU64::new(1);
726
727fn next_scoped_marker() -> u64 {
728 SCOPED_MARKER.fetch_add(1, Ordering::Relaxed)
729}
730
731#[repr(C)]
734struct ScopedHeader {
735 marker: u64,
736}
737
738#[repr(C)]
741struct ScopedCell<T> {
742 marker: u64,
743 cell: RefCell<Option<T>>,
744}
745
746unsafe extern "C" fn scoped_userdata_dtor<T>(ptr: *mut c_void) {
748 if !ptr.is_null() {
749 unsafe { core::ptr::drop_in_place(ptr as *mut ScopedCell<T>) };
750 }
751}
752
753unsafe fn recover_scoped_cell<'a, T>(
762 lua: &Lua,
763 value: &Value,
764 marker: u64,
765) -> Result<&'a ScopedCell<T>> {
766 match value {
767 Value::UserData(ud) => {
768 let state = lua.state();
769 unsafe {
770 ud.reference.push();
771 let ptr = lua_touserdata(state, -1);
772 lua_pop(state, 1);
773 if ptr.is_null() {
774 return Err(Error::UserDataTypeMismatch);
775 }
776 let header = &*(ptr as *const ScopedHeader);
777 if header.marker != marker {
778 return Err(Error::UserDataTypeMismatch);
779 }
780 Ok(&*(ptr as *const ScopedCell<T>))
781 }
782 }
783 _ => Err(Error::UserDataTypeMismatch),
784 }
785}
786
787struct ScopedCollector<T> {
792 marker: u64,
793 methods: Vec<Registered>,
794 fields: Vec<FieldEntry>,
795 _phantom: PhantomData<T>,
796}
797
798impl<T> ScopedCollector<T> {
799 fn new(marker: u64) -> Self {
800 ScopedCollector {
801 marker,
802 methods: Vec::new(),
803 fields: Vec::new(),
804 _phantom: PhantomData,
805 }
806 }
807}
808
809impl<T> UserDataMethods<T> for ScopedCollector<T> {
810 fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
811 where
812 M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
813 A: FromLuaMulti,
814 R: IntoLuaMulti,
815 {
816 let marker = self.marker;
817 let callback: BoxedCallback = Box::new(move |lua, mut args| {
818 let this = args.pop_front().unwrap_or(Value::Nil);
819 let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
820 let a = A::from_lua_multi(args, lua)?;
821 let borrowed = cell
822 .cell
823 .try_borrow()
824 .map_err(|_| Error::UserDataBorrowError)?;
825 let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
826 let r = method(lua, data, a)?;
827 r.into_lua_multi(lua)
828 });
829 self.methods.push(Registered {
830 name: name.into(),
831 is_meta: false,
832 callback,
833 });
834 }
835
836 fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
837 where
838 M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
839 A: FromLuaMulti,
840 R: IntoLuaMulti,
841 {
842 let marker = self.marker;
843 let callback: BoxedCallback = Box::new(move |lua, mut args| {
844 let this = args.pop_front().unwrap_or(Value::Nil);
845 let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
846 let a = A::from_lua_multi(args, lua)?;
847 let mut borrowed = cell
848 .cell
849 .try_borrow_mut()
850 .map_err(|_| Error::UserDataBorrowMutError)?;
851 let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
852 let r = method(lua, data, a)?;
853 r.into_lua_multi(lua)
854 });
855 self.methods.push(Registered {
856 name: name.into(),
857 is_meta: false,
858 callback,
859 });
860 }
861
862 fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
863 where
864 F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
865 A: FromLuaMulti,
866 R: IntoLuaMulti,
867 {
868 let callback: BoxedCallback = Box::new(move |lua, args| {
869 let a = A::from_lua_multi(args, lua)?;
870 let r = function(lua, a)?;
871 r.into_lua_multi(lua)
872 });
873 self.methods.push(Registered {
874 name: name.into(),
875 is_meta: false,
876 callback,
877 });
878 }
879
880 fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
881 where
882 M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
883 A: FromLuaMulti,
884 R: IntoLuaMulti,
885 {
886 let marker = self.marker;
887 let callback: BoxedCallback = Box::new(move |lua, mut args| {
888 let this = args.pop_front().unwrap_or(Value::Nil);
889 let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
890 let a = A::from_lua_multi(args, lua)?;
891 let borrowed = cell
892 .cell
893 .try_borrow()
894 .map_err(|_| Error::UserDataBorrowError)?;
895 let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
896 let r = method(lua, data, a)?;
897 r.into_lua_multi(lua)
898 });
899 self.methods.push(Registered {
900 name: name.into(),
901 is_meta: true,
902 callback,
903 });
904 }
905
906 fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
907 where
908 M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
909 A: FromLuaMulti,
910 R: IntoLuaMulti,
911 {
912 let marker = self.marker;
913 let callback: BoxedCallback = Box::new(move |lua, mut args| {
914 let this = args.pop_front().unwrap_or(Value::Nil);
915 let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
916 let a = A::from_lua_multi(args, lua)?;
917 let mut borrowed = cell
918 .cell
919 .try_borrow_mut()
920 .map_err(|_| Error::UserDataBorrowMutError)?;
921 let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
922 let r = method(lua, data, a)?;
923 r.into_lua_multi(lua)
924 });
925 self.methods.push(Registered {
926 name: name.into(),
927 is_meta: true,
928 callback,
929 });
930 }
931}
932
933impl<T> UserDataFields<T> for ScopedCollector<T> {
934 fn add_field<V>(&mut self, name: impl Into<String>, value: V)
935 where
936 V: IntoLua + Clone + MaybeSend + 'static,
937 {
938 let callback: BoxedCallback = Box::new(move |lua, _args| {
939 let v = value.clone().into_lua(lua)?;
940 v.into_lua_multi(lua)
941 });
942 self.fields.push(FieldEntry {
943 name: name.into(),
944 is_get: true,
945 callback,
946 });
947 }
948
949 fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
950 where
951 M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
952 R: IntoLua,
953 {
954 let marker = self.marker;
955 let callback: BoxedCallback = Box::new(move |lua, mut args| {
956 let this = args.pop_front().unwrap_or(Value::Nil);
957 let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
958 let borrowed = cell
959 .cell
960 .try_borrow()
961 .map_err(|_| Error::UserDataBorrowError)?;
962 let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
963 let r = method(lua, data)?;
964 r.into_lua_multi(lua)
965 });
966 self.fields.push(FieldEntry {
967 name: name.into(),
968 is_get: true,
969 callback,
970 });
971 }
972
973 fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
974 where
975 M: Fn(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
976 A: FromLua,
977 {
978 let marker = self.marker;
979 let callback: BoxedCallback = Box::new(move |lua, mut args| {
980 let this = args.pop_front().unwrap_or(Value::Nil);
981 let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
982 let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
983 let mut borrowed = cell
984 .cell
985 .try_borrow_mut()
986 .map_err(|_| Error::UserDataBorrowMutError)?;
987 let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
988 method(lua, data, val)?;
989 ().into_lua_multi(lua)
990 });
991 self.fields.push(FieldEntry {
992 name: name.into(),
993 is_get: false,
994 callback,
995 });
996 }
997
998 fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
999 where
1000 F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
1001 R: IntoLua,
1002 {
1003 let callback: BoxedCallback = Box::new(move |lua, mut args| {
1004 let this = args.pop_front().unwrap_or(Value::Nil);
1005 let ud = AnyUserData::from_lua(this, lua)?;
1006 let r = function(lua, ud)?;
1007 r.into_lua_multi(lua)
1008 });
1009 self.fields.push(FieldEntry {
1010 name: name.into(),
1011 is_get: true,
1012 callback,
1013 });
1014 }
1015
1016 fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
1017 where
1018 F: Fn(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
1019 A: FromLua,
1020 {
1021 let callback: BoxedCallback = Box::new(move |lua, mut args| {
1022 let this = args.pop_front().unwrap_or(Value::Nil);
1023 let ud = AnyUserData::from_lua(this, lua)?;
1024 let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
1025 function(lua, ud, val)?;
1026 ().into_lua_multi(lua)
1027 });
1028 self.fields.push(FieldEntry {
1029 name: name.into(),
1030 is_get: false,
1031 callback,
1032 });
1033 }
1034}
1035
1036fn install_index_dispatcher(
1050 lua: &Lua,
1051 metatable: &Table,
1052 method_table: Table,
1053 getters: Table,
1054 has_fields: bool,
1055) -> Result<()> {
1056 let user_index: Option<Function> = metatable.raw_get("__index")?;
1061
1062 if !has_fields && user_index.is_none() {
1063 metatable.set("__index", method_table)?;
1064 return Ok(());
1065 }
1066
1067 let index_fn = lua.create_function(move |_, (ud, key): (Value, Value)| {
1068 if has_fields {
1069 let getter: Value = getters.get(key.clone())?;
1070 if let Value::Function(f) = getter {
1071 return f.call::<Value>(ud);
1072 }
1073 }
1074 let method: Value = method_table.get(key.clone())?;
1075 if method != Value::Nil {
1076 return Ok(method);
1077 }
1078 match &user_index {
1079 Some(f) => f.call::<Value>((ud, key)),
1080 None => Ok(Value::Nil),
1081 }
1082 })?;
1083 metatable.set("__index", index_fn)?;
1084 Ok(())
1085}
1086
1087pub(crate) fn create_scoped_userdata<T: UserData>(
1100 lua: &Lua,
1101 data: T,
1102) -> Result<(AnyUserData, Box<dyn FnOnce()>)> {
1103 let state = lua.state();
1104 let marker = next_scoped_marker();
1105
1106 let mut collector = ScopedCollector::<T>::new(marker);
1108 T::add_fields(&mut collector);
1109 T::add_methods(&mut collector);
1110
1111 let method_table = lua.create_table();
1113 let metatable = lua.create_table();
1114 for item in collector.methods {
1115 let func = create_callback_function(lua, item.callback)?;
1116 if item.is_meta {
1117 metatable.set(item.name, func)?;
1118 } else {
1119 method_table.set(item.name, func)?;
1120 }
1121 }
1122
1123 let has_fields = !collector.fields.is_empty();
1124 let getters = lua.create_table();
1125 let setters = lua.create_table();
1126 for field in collector.fields {
1127 let func = create_callback_function(lua, field.callback)?;
1128 if field.is_get {
1129 getters.set(field.name, func)?;
1130 } else {
1131 setters.set(field.name, func)?;
1132 }
1133 }
1134
1135 if has_fields {
1136 let setters_c = setters.clone();
1137 let newindex_fn =
1138 lua.create_function(move |_, (ud, key, val): (Value, Value, Value)| {
1139 let setter: Value = setters_c.get(key.clone())?;
1140 if let Value::Function(f) = setter {
1141 f.call::<()>((ud, val))?;
1142 return Ok(());
1143 }
1144 let name = key.to_string().unwrap_or_default();
1145 Err(Error::RuntimeError(format!(
1146 "attempt to set unknown field '{name}' on userdata"
1147 )))
1148 })?;
1149 metatable.set("__newindex", newindex_fn)?;
1150 }
1151 install_index_dispatcher(lua, &metatable, method_table, getters, has_fields)?;
1152
1153 let ud = unsafe {
1155 let storage = lua_newuserdatadtor(
1156 state,
1157 core::mem::size_of::<ScopedCell<T>>(),
1158 Some(scoped_userdata_dtor::<T>),
1159 );
1160 if storage.is_null() {
1161 return Err(Error::runtime(
1162 "luaur-rt: failed to allocate scoped userdata",
1163 ));
1164 }
1165 core::ptr::write(
1166 storage as *mut ScopedCell<T>,
1167 ScopedCell {
1168 marker,
1169 cell: RefCell::new(Some(data)),
1170 },
1171 );
1172 metatable.push_to_stack();
1173 lua_setmetatable(state, -2);
1174 AnyUserData::from_ref(lua.pop_ref())
1175 };
1176
1177 let ud_for_dtor = ud.clone();
1180 let neutralise: Box<dyn FnOnce()> = Box::new(move || {
1181 let state = ud_for_dtor.reference.state();
1182 unsafe {
1183 ud_for_dtor.reference.push();
1184 let ptr = lua_touserdata(state, -1);
1185 lua_pop(state, 1);
1186 if ptr.is_null() {
1187 return;
1188 }
1189 let cell = &*(ptr as *const ScopedCell<T>);
1190 if let Ok(mut guard) = cell.cell.try_borrow_mut() {
1194 let _ = guard.take();
1195 }
1196 }
1197 });
1198
1199 Ok((ud, neutralise))
1200}
1201
1202pub(crate) fn create_userdata<T: UserData + MaybeSend + MaybeSync + 'static>(
1205 lua: &Lua,
1206 data: T,
1207) -> Result<AnyUserData> {
1208 let state = lua.state();
1209
1210 let mut collector = Collector::<T>::new();
1212 T::add_fields(&mut collector);
1213 T::add_methods(&mut collector);
1214
1215 let method_table = lua.create_table();
1218 let metatable = lua.create_table();
1219 for item in collector.methods {
1220 let func = create_callback_function(lua, item.callback)?;
1221 if item.is_meta {
1222 metatable.set(item.name, func)?;
1223 } else {
1224 method_table.set(item.name, func)?;
1225 }
1226 }
1227
1228 let has_fields = !collector.fields.is_empty();
1229 let getters = lua.create_table();
1230 let setters = lua.create_table();
1231 for field in collector.fields {
1232 let func = create_callback_function(lua, field.callback)?;
1233 if field.is_get {
1234 getters.set(field.name, func)?;
1235 } else {
1236 setters.set(field.name, func)?;
1237 }
1238 }
1239
1240 if has_fields {
1241 let setters_c = setters.clone();
1243 let newindex_fn =
1244 lua.create_function(move |_, (ud, key, val): (Value, Value, Value)| {
1245 let setter: Value = setters_c.get(key.clone())?;
1246 if let Value::Function(f) = setter {
1247 f.call::<()>((ud, val))?;
1248 return Ok(());
1249 }
1250 let name = key.to_string().unwrap_or_default();
1251 Err(Error::RuntimeError(format!(
1252 "attempt to set unknown field '{name}' on userdata"
1253 )))
1254 })?;
1255 metatable.set("__newindex", newindex_fn)?;
1256 }
1257 install_index_dispatcher(lua, &metatable, method_table, getters, has_fields)?;
1259
1260 unsafe {
1262 let storage = lua_newuserdatadtor(
1263 state,
1264 core::mem::size_of::<UserDataCell<T>>(),
1265 Some(userdata_dtor::<T>),
1266 );
1267 if storage.is_null() {
1268 return Err(Error::runtime("luaur-rt: failed to allocate userdata"));
1269 }
1270 core::ptr::write(
1271 storage as *mut UserDataCell<T>,
1272 UserDataCell {
1273 type_id: TypeId::of::<T>(),
1274 cell: RefCell::new(Some(data)),
1275 },
1276 );
1277
1278 metatable.push_to_stack();
1280 lua_setmetatable(state, -2);
1281
1282 Ok(AnyUserData::from_ref(lua.pop_ref()))
1284 }
1285}