Skip to main content

luaur_rt/
userdata.rs

1//! [`UserData`] / [`UserDataMethods`] / [`UserDataFields`] and the
2//! [`AnyUserData`] handle. Mirrors `mlua::UserData` / `mlua::UserDataMethods` /
3//! `mlua::UserDataFields` / `mlua::AnyUserData`.
4//!
5//! ## Implementation
6//!
7//! A `T: UserData` value is boxed into a Lua userdata as a typed wrapper
8//! [`UserDataCell<T>`] = `{ type_id, RefCell<Option<T>> }` (via
9//! [`lua_newuserdatadtor`], whose destructor drops the cell). The leading
10//! `TypeId` makes Rust-side typed read-back **sound**: every accessor
11//! ([`AnyUserData::borrow`], [`borrow_mut`](AnyUserData::borrow_mut),
12//! [`take`](AnyUserData::take), [`is`](AnyUserData::is)) reads the stored
13//! `TypeId` from the userdata pointer and compares it with `TypeId::of::<T>()`
14//! before downcasting — a mismatch is an [`Error::UserDataTypeMismatch`].
15//! `take` replaces the `Option<T>` with `None`; subsequent access reports
16//! [`Error::UserDataDestructed`].
17//!
18//! Each registered method/field is compiled into a Rust closure wired into a
19//! per-instance metatable:
20//!   - ordinary methods go into a method table,
21//!   - field getters/setters are dispatched by an `__index`/`__newindex`
22//!     function (only when fields are registered),
23//!   - meta-methods (e.g. `__add`) go directly on the metatable.
24
25use 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
39/// A Rust type that can be exposed to Lua as userdata.
40///
41/// Mirrors `mlua::UserData`. Implement [`UserData::add_methods`] and/or
42/// [`UserData::add_fields`] to register the surface visible from Lua.
43pub trait UserData: Sized {
44    /// Register fields (getters/setters). Default: none.
45    fn add_fields<F: UserDataFields<Self>>(_fields: &mut F) {}
46
47    /// Register methods and meta-methods. Default: none.
48    fn add_methods<M: UserDataMethods<Self>>(_methods: &mut M) {}
49}
50
51/// Registrar passed to [`UserData::add_methods`].
52///
53/// Mirrors `mlua::UserDataMethods`.
54pub trait UserDataMethods<T> {
55    /// Register a method callable as `obj:name(...)`; receives `&T`.
56    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    /// Register a method callable as `obj:name(...)`; receives `&mut T`.
63    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    /// Register a plain function in the userdata namespace (no `self`).
70    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    /// Register a meta-method (e.g. `MetaMethod::Add`, `"__tostring"`);
77    /// receives `&T`.
78    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    /// Register a meta-method receiving `&mut T`.
85    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
92/// Registrar passed to [`UserData::add_fields`].
93///
94/// Mirrors `mlua::UserDataFields`. Field getters/setters are dispatched by the
95/// userdata's `__index`/`__newindex`.
96pub trait UserDataFields<T> {
97    /// Register a constant field value (read-only).
98    fn add_field<V>(&mut self, name: impl Into<String>, value: V)
99    where
100        V: IntoLua + Clone + MaybeSend + 'static;
101
102    /// Register a field whose getter receives `&T`.
103    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    /// Register a field whose setter receives `&mut T` and the assigned value.
109    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    /// Register a field whose getter receives the [`AnyUserData`] handle.
115    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    /// Register a field whose setter receives the [`AnyUserData`] handle and
121    /// the assigned value.
122    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/// A handle to an arbitrary Lua userdata value.
129///
130/// Mirrors `mlua::AnyUserData`. Supports construction, use-from-Lua, and typed
131/// Rust-side borrowing ([`borrow`](AnyUserData::borrow) /
132/// [`borrow_mut`](AnyUserData::borrow_mut) / [`take`](AnyUserData::take) /
133/// [`is`](AnyUserData::is)).
134#[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    /// The owning [`Lua`].
153    pub fn lua(&self) -> Lua {
154        self.reference.lua()
155    }
156
157    /// A raw pointer identifying this userdata. Mirrors
158    /// `mlua::AnyUserData::to_pointer`.
159    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    /// Compare for equality honoring an `__eq` metamethod.
170    /// Mirrors `mlua::AnyUserData::equals`.
171    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    /// Recover a `&UserDataCell<T>` from the userdata storage, checking the
184    /// embedded `TypeId`. Returns `UserDataTypeMismatch` if the concrete type
185    /// differs.
186    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            // The wrapper stores the TypeId first; check it before downcasting.
196            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    /// Whether the stored value is of concrete type `T`. Mirrors
205    /// `mlua::AnyUserData::is`. Returns `false` after the value has been taken.
206    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    /// The [`TypeId`] of the stored value, if it is a luaur-rt userdata.
214    /// Mirrors `mlua::AnyUserData::type_id` (here it returns the concrete
215    /// `TypeId` whenever the userdata carries a luaur-rt wrapper header).
216    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            // Only luaur-rt userdata carry a header; raw VM userdata do not, but
226            // every userdata this crate creates does.
227            let header = &*(ptr as *const UserDataHeader);
228            Some(header.type_id)
229        }
230    }
231
232    /// Immutably borrow the stored value as `T`. Mirrors
233    /// `mlua::AnyUserData::borrow`. Errors with [`Error::UserDataTypeMismatch`]
234    /// on a type mismatch, [`Error::UserDataDestructed`] if it was taken, or
235    /// [`Error::UserDataBorrowError`] if already mutably borrowed.
236    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    /// Mutably borrow the stored value as `T`. Mirrors
252    /// `mlua::AnyUserData::borrow_mut`.
253    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    /// Take the stored value out of the userdata, leaving it destructed.
269    /// Mirrors `mlua::AnyUserData::take`. Errors with
270    /// [`Error::UserDataBorrowMutError`] if currently borrowed, or
271    /// [`Error::UserDataDestructed`] if already taken.
272    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
282/// A RAII guard for an immutable userdata borrow ([`AnyUserData::borrow`]).
283/// Mirrors `mlua::UserDataRef`.
284pub 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        // Invariant: `borrow` returns only when the option is `Some`.
293        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
309/// A RAII guard for a mutable userdata borrow ([`AnyUserData::borrow_mut`]).
310/// Mirrors `mlua::UserDataRefMut`.
311pub 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        // Pointer identity (matches mlua): same underlying userdata object.
350        self.to_pointer() == other.to_pointer()
351    }
352}
353
354// Any `T: UserData` value converts into Lua by wrapping it in a fresh userdata.
355// Mirrors mlua's `impl<T: UserData + MaybeSend + MaybeSync + 'static> IntoLua`.
356// This is what lets `create_registry_value(MyUserdata(..))`,
357// `table.set("k", MyUserdata(..))`, etc. accept a userdata value directly. It
358// coexists with the concrete `IntoLua` impls below because none of those
359// (local) types implement `UserData`.
360impl<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// ---------------------------------------------------------------------------
392// Typed userdata storage
393// ---------------------------------------------------------------------------
394
395/// The fixed leading layout of every luaur-rt userdata wrapper. Reading the
396/// `TypeId` through this header (a prefix of [`UserDataCell<T>`]) lets us check
397/// the concrete type before downcasting. The two share `#[repr(C)]` so the
398/// `type_id` field is at the same offset for any `T`.
399#[repr(C)]
400struct UserDataHeader {
401    type_id: TypeId,
402}
403
404/// The typed userdata storage: a `TypeId` followed by the `RefCell<Option<T>>`.
405#[repr(C)]
406struct UserDataCell<T> {
407    type_id: TypeId,
408    cell: RefCell<Option<T>>,
409}
410
411/// Recover `&UserDataCell<T>` from a `self` userdata [`Value`] (Lua argument 1).
412fn 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
434// ---------------------------------------------------------------------------
435// Method collection
436// ---------------------------------------------------------------------------
437
438/// A registered method or meta-method, paired with its name and whether it is a
439/// meta-method.
440struct Registered {
441    name: String,
442    is_meta: bool,
443    callback: BoxedCallback,
444}
445
446/// A registered field getter or setter.
447struct FieldEntry {
448    name: String,
449    /// `true` if a getter, `false` if a setter.
450    is_get: bool,
451    callback: BoxedCallback,
452}
453
454/// Concrete [`UserDataMethods`] / [`UserDataFields`] implementation that
455/// collects the type-erased callbacks; the metatable is built from these.
456struct 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
693/// Destructor for the [`UserDataCell<T>`] stored inside the userdata.
694unsafe 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
700// ---------------------------------------------------------------------------
701// Scoped (non-'static) userdata — used by `Lua::scope`
702// ---------------------------------------------------------------------------
703//
704// Ordinary userdata stores a `TypeId` so values can be soundly read back out by
705// concrete type (`borrow`/`take`/`is`). That requires `T: 'static`.
706//
707// A scope can create userdata wrapping a **non-`'static`** `T` (e.g. one that
708// borrows from the enclosing stack frame). For these there is no `TypeId`, so
709// instead each scoped userdata is tagged with a process-unique `u64` **marker**.
710// Every method/field/meta closure for that userdata captures the *same* marker,
711// so on dispatch it can confirm the `self` it received is exactly the userdata
712// it belongs to (recovering `&ScopedCell<T>` is sound only after the marker
713// matches — markers are never reused, so no other userdata can collide).
714//
715// Soundness over the scope lifetime: while the scope is active the wrapped `T`
716// is `Some` and methods may form a transient `&T`/`&mut T`. On scope exit the
717// scope's destructor `take()`s the value to `None` (dropping the borrowed `T`,
718// ending its borrows) but leaves the cell memory valid; any later dispatch finds
719// `None` and returns `Error::UserDataDestructed`. The cell itself is freed only
720// when the GC collects the userdata, never while a `&ScopedCell<T>` could exist.
721
722use std::sync::atomic::{AtomicU64, Ordering};
723
724/// Source of process-unique scoped-userdata markers.
725static SCOPED_MARKER: AtomicU64 = AtomicU64::new(1);
726
727fn next_scoped_marker() -> u64 {
728    SCOPED_MARKER.fetch_add(1, Ordering::Relaxed)
729}
730
731/// The fixed leading layout of a scoped userdata wrapper: a unique marker used
732/// to recognise the instance (in place of a `TypeId`).
733#[repr(C)]
734struct ScopedHeader {
735    marker: u64,
736}
737
738/// Scoped userdata storage: a unique marker followed by the data cell. Shares
739/// `#[repr(C)]` with [`ScopedHeader`] so the marker is at offset 0 for any `T`.
740#[repr(C)]
741struct ScopedCell<T> {
742    marker: u64,
743    cell: RefCell<Option<T>>,
744}
745
746/// Destructor for the [`ScopedCell<T>`] stored inside a scoped userdata.
747unsafe 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
753/// Recover `&ScopedCell<T>` from a `self` userdata [`Value`] (Lua argument 1),
754/// verifying the per-instance `marker`. A mismatch is an
755/// [`Error::UserDataTypeMismatch`].
756///
757/// # Safety
758/// The caller guarantees that any userdata carrying `marker` was created as a
759/// `ScopedCell<T>` for this exact `T` (which holds because each marker is handed
760/// out to exactly one `create_scoped_userdata::<T>` call).
761unsafe 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
787/// A concrete [`UserDataMethods`] / [`UserDataFields`] implementation for a
788/// scoped (non-`'static`) userdata instance: identical surface to [`Collector`],
789/// but it recovers the data cell by the per-instance `marker` rather than a
790/// `TypeId`, so it works for non-`'static` `T`.
791struct 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
1036/// Install the userdata metatable's `__index`.
1037///
1038/// Mirrors mlua's generated `__index` (`mlua::userdata::util`): a lookup falls
1039/// through **field getters → the method table → a user-registered `__index`
1040/// meta-method**. A custom `__index` set by [`UserDataMethods::add_meta_method`]
1041/// therefore stays reachable instead of being overwritten by the method table
1042/// or the field dispatcher.
1043///
1044/// The cheap case — no fields and no custom `__index` — keeps `__index` as the
1045/// method table itself, so ordinary method lookup stays a plain table access.
1046///
1047/// DEVIATION from mlua: an unresolved key yields `nil` rather than raising
1048/// "attempt to get an unknown field", matching luaur-rt's existing behavior.
1049fn install_index_dispatcher(
1050    lua: &Lua,
1051    metatable: &Table,
1052    method_table: Table,
1053    getters: Table,
1054    has_fields: bool,
1055) -> Result<()> {
1056    // A custom `__index` was written onto the metatable by the meta-method loop
1057    // above; capture it here so the dispatcher can fall back to it. Only
1058    // functions can land there (`add_meta_method`/`add_meta_method_mut` are the
1059    // only ways in), so a non-function `__index` is not representable.
1060    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
1087/// Build a scoped (non-`'static`) userdata wrapping `data`, with a metatable
1088/// assembled from `T::add_fields` + `T::add_methods`. Returns the
1089/// [`AnyUserData`] handle plus a closure that, when called, neutralises the
1090/// userdata (drops `data`, leaving later access to error with
1091/// [`Error::UserDataDestructed`]). The neutraliser is what `Lua::scope`
1092/// registers as a destructor.
1093///
1094/// # Safety
1095/// The returned [`AnyUserData`] must not be used to read `data` back out by
1096/// type (there is no `TypeId`); only metatable-driven method/field/meta dispatch
1097/// is supported. The scope must invoke the returned neutraliser before `data`'s
1098/// borrowed lifetime ends.
1099pub(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    // 1. Collect fields, methods, and meta-methods (marker-keyed recovery).
1107    let mut collector = ScopedCollector::<T>::new(marker);
1108    T::add_fields(&mut collector);
1109    T::add_methods(&mut collector);
1110
1111    // 2. Build the method table + meta-methods + field getter/setter tables.
1112    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    // 3. Allocate the scoped userdata holding ScopedCell<T> and move `data` in.
1154    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    // 4. Build the neutraliser: on scope exit, take the data out of the cell,
1178    //    dropping the (possibly borrowing) `T` while the cell memory stays valid.
1179    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            // Drop the data (ends borrows). If currently borrowed (a method is
1191            // somehow live), `try_borrow_mut` fails and we leave it — but scope
1192            // exit only happens after `f` returns, so no method is in flight.
1193            if let Ok(mut guard) = cell.cell.try_borrow_mut() {
1194                let _ = guard.take();
1195            }
1196        }
1197    });
1198
1199    Ok((ud, neutralise))
1200}
1201
1202/// Build a userdata value wrapping `data`, with a metatable assembled from the
1203/// type's [`UserData::add_fields`] + [`UserData::add_methods`].
1204pub(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    // 1. Collect fields, methods, and meta-methods.
1211    let mut collector = Collector::<T>::new();
1212    T::add_fields(&mut collector);
1213    T::add_methods(&mut collector);
1214
1215    // 2. Build the method table + meta-methods, and the field getter/setter
1216    //    tables (if any fields were registered).
1217    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        // __newindex dispatcher: try a field setter, else raise.
1242        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    // __index: field getters -> method table -> a custom `__index` meta-method.
1258    install_index_dispatcher(lua, &metatable, method_table, getters, has_fields)?;
1259
1260    // 3. Allocate the userdata holding UserDataCell<T> and move `data` in.
1261    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        // 4. Set the metatable on the userdata (which is on top of stack).
1279        metatable.push_to_stack();
1280        lua_setmetatable(state, -2);
1281
1282        // 5. Take a ref to the userdata and return.
1283        Ok(AnyUserData::from_ref(lua.pop_ref()))
1284    }
1285}