luaur-rt 0.1.3

Safe, ergonomic, mlua-style API for luaur (pure-Rust Luau).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
//! [`UserData`] / [`UserDataMethods`] / [`UserDataFields`] and the
//! [`AnyUserData`] handle. Mirrors `mlua::UserData` / `mlua::UserDataMethods` /
//! `mlua::UserDataFields` / `mlua::AnyUserData`.
//!
//! ## Implementation
//!
//! A `T: UserData` value is boxed into a Lua userdata as a typed wrapper
//! [`UserDataCell<T>`] = `{ type_id, RefCell<Option<T>> }` (via
//! [`lua_newuserdatadtor`], whose destructor drops the cell). The leading
//! `TypeId` makes Rust-side typed read-back **sound**: every accessor
//! ([`AnyUserData::borrow`], [`borrow_mut`](AnyUserData::borrow_mut),
//! [`take`](AnyUserData::take), [`is`](AnyUserData::is)) reads the stored
//! `TypeId` from the userdata pointer and compares it with `TypeId::of::<T>()`
//! before downcasting — a mismatch is an [`Error::UserDataTypeMismatch`].
//! `take` replaces the `Option<T>` with `None`; subsequent access reports
//! [`Error::UserDataDestructed`].
//!
//! Each registered method/field is compiled into a Rust closure wired into a
//! per-instance metatable:
//!   - ordinary methods go into a method table,
//!   - field getters/setters are dispatched by an `__index`/`__newindex`
//!     function (only when fields are registered),
//!   - meta-methods (e.g. `__add`) go directly on the metatable.

use std::any::TypeId;
use std::cell::RefCell;
use std::marker::PhantomData;

use crate::callback::{create_callback_function, BoxedCallback};
use crate::error::{Error, Result};
use crate::state::{Lua, LuaRef};
use crate::sync::{MaybeSend, MaybeSync, NotSync, XRc, NOT_SYNC};
use crate::sys::*;
use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
use crate::value::Value;

/// A Rust type that can be exposed to Lua as userdata.
///
/// Mirrors `mlua::UserData`. Implement [`UserData::add_methods`] and/or
/// [`UserData::add_fields`] to register the surface visible from Lua.
pub trait UserData: Sized {
    /// Register fields (getters/setters). Default: none.
    fn add_fields<F: UserDataFields<Self>>(_fields: &mut F) {}

    /// Register methods and meta-methods. Default: none.
    fn add_methods<M: UserDataMethods<Self>>(_methods: &mut M) {}
}

/// Registrar passed to [`UserData::add_methods`].
///
/// Mirrors `mlua::UserDataMethods`.
pub trait UserDataMethods<T> {
    /// Register a method callable as `obj:name(...)`; receives `&T`.
    fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti;

    /// Register a method callable as `obj:name(...)`; receives `&mut T`.
    fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti;

    /// Register a plain function in the userdata namespace (no `self`).
    fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti;

    /// Register a meta-method (e.g. `MetaMethod::Add`, `"__tostring"`);
    /// receives `&T`.
    fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti;

    /// Register a meta-method receiving `&mut T`.
    fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti;
}

/// Registrar passed to [`UserData::add_fields`].
///
/// Mirrors `mlua::UserDataFields`. Field getters/setters are dispatched by the
/// userdata's `__index`/`__newindex`.
pub trait UserDataFields<T> {
    /// Register a constant field value (read-only).
    fn add_field<V>(&mut self, name: impl Into<String>, value: V)
    where
        V: IntoLua + Clone + MaybeSend + 'static;

    /// Register a field whose getter receives `&T`.
    fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
        R: IntoLua;

    /// Register a field whose setter receives `&mut T` and the assigned value.
    fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
        A: FromLua;

    /// Register a field whose getter receives the [`AnyUserData`] handle.
    fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
        R: IntoLua;

    /// Register a field whose setter receives the [`AnyUserData`] handle and
    /// the assigned value.
    fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
        A: FromLua;
}

/// A handle to an arbitrary Lua userdata value.
///
/// Mirrors `mlua::AnyUserData`. Supports construction, use-from-Lua, and typed
/// Rust-side borrowing ([`borrow`](AnyUserData::borrow) /
/// [`borrow_mut`](AnyUserData::borrow_mut) / [`take`](AnyUserData::take) /
/// [`is`](AnyUserData::is)).
#[derive(Clone)]
pub struct AnyUserData {
    pub(crate) reference: XRc<LuaRef>,
    pub(crate) _not_sync: NotSync,
}

impl AnyUserData {
    pub(crate) fn from_ref(reference: LuaRef) -> AnyUserData {
        AnyUserData {
            reference: XRc::new(reference),
            _not_sync: NOT_SYNC,
        }
    }

    pub(crate) unsafe fn push_to_stack(&self) {
        self.reference.push();
    }

    /// The owning [`Lua`].
    pub fn lua(&self) -> Lua {
        self.reference.lua()
    }

    /// A raw pointer identifying this userdata. Mirrors
    /// `mlua::AnyUserData::to_pointer`.
    pub fn to_pointer(&self) -> *const c_void {
        let state = self.reference.state();
        unsafe {
            self.reference.push();
            let p = lua_topointer(state, -1);
            lua_pop(state, 1);
            p
        }
    }

    /// Compare for equality honoring an `__eq` metamethod.
    /// Mirrors `mlua::AnyUserData::equals`.
    pub fn equals(&self, other: &AnyUserData) -> Result<bool> {
        let lua = self.lua();
        let state = lua.state();
        unsafe {
            self.reference.push();
            other.reference.push();
            let eq = lua_equal(state, -2, -1);
            lua_pop(state, 2);
            Ok(eq != 0)
        }
    }

    /// Recover a `&UserDataCell<T>` from the userdata storage, checking the
    /// embedded `TypeId`. Returns `UserDataTypeMismatch` if the concrete type
    /// differs.
    fn cell<T: 'static>(&self) -> Result<&UserDataCell<T>> {
        let state = self.reference.state();
        unsafe {
            self.reference.push();
            let ptr = lua_touserdata(state, -1);
            lua_pop(state, 1);
            if ptr.is_null() {
                return Err(Error::UserDataTypeMismatch);
            }
            // The wrapper stores the TypeId first; check it before downcasting.
            let header = &*(ptr as *const UserDataHeader);
            if header.type_id != TypeId::of::<T>() {
                return Err(Error::UserDataTypeMismatch);
            }
            Ok(&*(ptr as *const UserDataCell<T>))
        }
    }

    /// Whether the stored value is of concrete type `T`. Mirrors
    /// `mlua::AnyUserData::is`. Returns `false` after the value has been taken.
    pub fn is<T: 'static>(&self) -> bool {
        match self.cell::<T>() {
            Ok(cell) => cell.cell.borrow().is_some(),
            Err(_) => false,
        }
    }

    /// The [`TypeId`] of the stored value, if it is a luaur-rt userdata.
    /// Mirrors `mlua::AnyUserData::type_id` (here it returns the concrete
    /// `TypeId` whenever the userdata carries a luaur-rt wrapper header).
    pub fn type_id(&self) -> Option<TypeId> {
        let state = self.reference.state();
        unsafe {
            self.reference.push();
            let ptr = lua_touserdata(state, -1);
            lua_pop(state, 1);
            if ptr.is_null() {
                return None;
            }
            // Only luaur-rt userdata carry a header; raw VM userdata do not, but
            // every userdata this crate creates does.
            let header = &*(ptr as *const UserDataHeader);
            Some(header.type_id)
        }
    }

    /// Immutably borrow the stored value as `T`. Mirrors
    /// `mlua::AnyUserData::borrow`. Errors with [`Error::UserDataTypeMismatch`]
    /// on a type mismatch, [`Error::UserDataDestructed`] if it was taken, or
    /// [`Error::UserDataBorrowError`] if already mutably borrowed.
    pub fn borrow<T: 'static>(&self) -> Result<UserDataRef<'_, T>> {
        let cell = self.cell::<T>()?;
        let guard = cell
            .cell
            .try_borrow()
            .map_err(|_| Error::UserDataBorrowError)?;
        if guard.is_none() {
            return Err(Error::UserDataDestructed);
        }
        Ok(UserDataRef {
            guard,
            _marker: PhantomData,
        })
    }

    /// Mutably borrow the stored value as `T`. Mirrors
    /// `mlua::AnyUserData::borrow_mut`.
    pub fn borrow_mut<T: 'static>(&self) -> Result<UserDataRefMut<'_, T>> {
        let cell = self.cell::<T>()?;
        let guard = cell
            .cell
            .try_borrow_mut()
            .map_err(|_| Error::UserDataBorrowMutError)?;
        if guard.is_none() {
            return Err(Error::UserDataDestructed);
        }
        Ok(UserDataRefMut {
            guard,
            _marker: PhantomData,
        })
    }

    /// Take the stored value out of the userdata, leaving it destructed.
    /// Mirrors `mlua::AnyUserData::take`. Errors with
    /// [`Error::UserDataBorrowMutError`] if currently borrowed, or
    /// [`Error::UserDataDestructed`] if already taken.
    pub fn take<T: 'static>(&self) -> Result<T> {
        let cell = self.cell::<T>()?;
        let mut guard = cell
            .cell
            .try_borrow_mut()
            .map_err(|_| Error::UserDataBorrowMutError)?;
        guard.take().ok_or(Error::UserDataDestructed)
    }
}

/// A RAII guard for an immutable userdata borrow ([`AnyUserData::borrow`]).
/// Mirrors `mlua::UserDataRef`.
pub struct UserDataRef<'a, T> {
    guard: std::cell::Ref<'a, Option<T>>,
    _marker: PhantomData<T>,
}

impl<T> std::ops::Deref for UserDataRef<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        // Invariant: `borrow` returns only when the option is `Some`.
        self.guard.as_ref().expect("userdata destructed")
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for UserDataRef<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&**self, f)
    }
}

impl<T: std::fmt::Display> std::fmt::Display for UserDataRef<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&**self, f)
    }
}

/// A RAII guard for a mutable userdata borrow ([`AnyUserData::borrow_mut`]).
/// Mirrors `mlua::UserDataRefMut`.
pub struct UserDataRefMut<'a, T> {
    guard: std::cell::RefMut<'a, Option<T>>,
    _marker: PhantomData<T>,
}

impl<T> std::ops::Deref for UserDataRefMut<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.guard.as_ref().expect("userdata destructed")
    }
}

impl<T> std::ops::DerefMut for UserDataRefMut<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.guard.as_mut().expect("userdata destructed")
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for UserDataRefMut<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&**self, f)
    }
}

impl<T: std::fmt::Display> std::fmt::Display for UserDataRefMut<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&**self, f)
    }
}

impl std::fmt::Debug for AnyUserData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UserData")
    }
}

impl PartialEq for AnyUserData {
    fn eq(&self, other: &Self) -> bool {
        // Pointer identity (matches mlua): same underlying userdata object.
        self.to_pointer() == other.to_pointer()
    }
}

// Any `T: UserData` value converts into Lua by wrapping it in a fresh userdata.
// Mirrors mlua's `impl<T: UserData + MaybeSend + MaybeSync + 'static> IntoLua`.
// This is what lets `create_registry_value(MyUserdata(..))`,
// `table.set("k", MyUserdata(..))`, etc. accept a userdata value directly. It
// coexists with the concrete `IntoLua` impls below because none of those
// (local) types implement `UserData`.
impl<T: UserData + crate::sync::MaybeSend + crate::sync::MaybeSync + 'static> IntoLua for T {
    fn into_lua(self, lua: &Lua) -> Result<Value> {
        Ok(Value::UserData(lua.create_userdata(self)?))
    }
}

impl IntoLua for AnyUserData {
    fn into_lua(self, _lua: &Lua) -> Result<Value> {
        Ok(Value::UserData(self))
    }
}

impl IntoLua for &AnyUserData {
    fn into_lua(self, _lua: &Lua) -> Result<Value> {
        Ok(Value::UserData(self.clone()))
    }
}

impl FromLua for AnyUserData {
    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
        match value {
            Value::UserData(ud) => Ok(ud),
            other => Err(Error::FromLuaConversionError {
                from: other.type_name(),
                to: "AnyUserData".to_string(),
                message: None,
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// Typed userdata storage
// ---------------------------------------------------------------------------

/// The fixed leading layout of every luaur-rt userdata wrapper. Reading the
/// `TypeId` through this header (a prefix of [`UserDataCell<T>`]) lets us check
/// the concrete type before downcasting. The two share `#[repr(C)]` so the
/// `type_id` field is at the same offset for any `T`.
#[repr(C)]
struct UserDataHeader {
    type_id: TypeId,
}

/// The typed userdata storage: a `TypeId` followed by the `RefCell<Option<T>>`.
#[repr(C)]
struct UserDataCell<T> {
    type_id: TypeId,
    cell: RefCell<Option<T>>,
}

/// Recover `&UserDataCell<T>` from a `self` userdata [`Value`] (Lua argument 1).
fn recover_cell<'a, T: 'static>(lua: &Lua, value: &Value) -> Result<&'a UserDataCell<T>> {
    match value {
        Value::UserData(ud) => {
            let state = lua.state();
            unsafe {
                ud.reference.push();
                let ptr = lua_touserdata(state, -1);
                lua_pop(state, 1);
                if ptr.is_null() {
                    return Err(Error::UserDataTypeMismatch);
                }
                let header = &*(ptr as *const UserDataHeader);
                if header.type_id != TypeId::of::<T>() {
                    return Err(Error::UserDataTypeMismatch);
                }
                Ok(&*(ptr as *const UserDataCell<T>))
            }
        }
        _ => Err(Error::UserDataTypeMismatch),
    }
}

// ---------------------------------------------------------------------------
// Method collection
// ---------------------------------------------------------------------------

/// A registered method or meta-method, paired with its name and whether it is a
/// meta-method.
struct Registered {
    name: String,
    is_meta: bool,
    callback: BoxedCallback,
}

/// A registered field getter or setter.
struct FieldEntry {
    name: String,
    /// `true` if a getter, `false` if a setter.
    is_get: bool,
    callback: BoxedCallback,
}

/// Concrete [`UserDataMethods`] / [`UserDataFields`] implementation that
/// collects the type-erased callbacks; the metatable is built from these.
struct Collector<T> {
    methods: Vec<Registered>,
    fields: Vec<FieldEntry>,
    _phantom: PhantomData<T>,
}

impl<T> Collector<T> {
    fn new() -> Self {
        Collector {
            methods: Vec::new(),
            fields: Vec::new(),
            _phantom: PhantomData,
        }
    }
}

impl<T: 'static> UserDataMethods<T> for Collector<T> {
    fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = recover_cell::<T>(lua, &this)?;
            let a = A::from_lua_multi(args, lua)?;
            let borrowed = cell
                .cell
                .try_borrow()
                .map_err(|_| Error::UserDataBorrowError)?;
            let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: false,
            callback,
        });
    }

    fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = recover_cell::<T>(lua, &this)?;
            let a = A::from_lua_multi(args, lua)?;
            let mut borrowed = cell
                .cell
                .try_borrow_mut()
                .map_err(|_| Error::UserDataBorrowMutError)?;
            let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: false,
            callback,
        });
    }

    fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let callback: BoxedCallback = Box::new(move |lua, args| {
            let a = A::from_lua_multi(args, lua)?;
            let r = function(lua, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: false,
            callback,
        });
    }

    fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = recover_cell::<T>(lua, &this)?;
            let a = A::from_lua_multi(args, lua)?;
            let borrowed = cell
                .cell
                .try_borrow()
                .map_err(|_| Error::UserDataBorrowError)?;
            let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: true,
            callback,
        });
    }

    fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = recover_cell::<T>(lua, &this)?;
            let a = A::from_lua_multi(args, lua)?;
            let mut borrowed = cell
                .cell
                .try_borrow_mut()
                .map_err(|_| Error::UserDataBorrowMutError)?;
            let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: true,
            callback,
        });
    }
}

impl<T: 'static> UserDataFields<T> for Collector<T> {
    fn add_field<V>(&mut self, name: impl Into<String>, value: V)
    where
        V: IntoLua + Clone + MaybeSend + 'static,
    {
        let callback: BoxedCallback = Box::new(move |lua, _args| {
            let v = value.clone().into_lua(lua)?;
            v.into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: true,
            callback,
        });
    }

    fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
        R: IntoLua,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = recover_cell::<T>(lua, &this)?;
            let borrowed = cell
                .cell
                .try_borrow()
                .map_err(|_| Error::UserDataBorrowError)?;
            let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data)?;
            r.into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: true,
            callback,
        });
    }

    fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
        A: FromLua,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = recover_cell::<T>(lua, &this)?;
            let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
            let mut borrowed = cell
                .cell
                .try_borrow_mut()
                .map_err(|_| Error::UserDataBorrowMutError)?;
            let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
            method(lua, data, val)?;
            ().into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: false,
            callback,
        });
    }

    fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
        R: IntoLua,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let ud = AnyUserData::from_lua(this, lua)?;
            let r = function(lua, ud)?;
            r.into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: true,
            callback,
        });
    }

    fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
        A: FromLua,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let ud = AnyUserData::from_lua(this, lua)?;
            let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
            function(lua, ud, val)?;
            ().into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: false,
            callback,
        });
    }
}

/// Destructor for the [`UserDataCell<T>`] stored inside the userdata.
unsafe extern "C" fn userdata_dtor<T>(ptr: *mut c_void) {
    if !ptr.is_null() {
        unsafe { core::ptr::drop_in_place(ptr as *mut UserDataCell<T>) };
    }
}

// ---------------------------------------------------------------------------
// Scoped (non-'static) userdata — used by `Lua::scope`
// ---------------------------------------------------------------------------
//
// Ordinary userdata stores a `TypeId` so values can be soundly read back out by
// concrete type (`borrow`/`take`/`is`). That requires `T: 'static`.
//
// A scope can create userdata wrapping a **non-`'static`** `T` (e.g. one that
// borrows from the enclosing stack frame). For these there is no `TypeId`, so
// instead each scoped userdata is tagged with a process-unique `u64` **marker**.
// Every method/field/meta closure for that userdata captures the *same* marker,
// so on dispatch it can confirm the `self` it received is exactly the userdata
// it belongs to (recovering `&ScopedCell<T>` is sound only after the marker
// matches — markers are never reused, so no other userdata can collide).
//
// Soundness over the scope lifetime: while the scope is active the wrapped `T`
// is `Some` and methods may form a transient `&T`/`&mut T`. On scope exit the
// scope's destructor `take()`s the value to `None` (dropping the borrowed `T`,
// ending its borrows) but leaves the cell memory valid; any later dispatch finds
// `None` and returns `Error::UserDataDestructed`. The cell itself is freed only
// when the GC collects the userdata, never while a `&ScopedCell<T>` could exist.

use std::sync::atomic::{AtomicU64, Ordering};

/// Source of process-unique scoped-userdata markers.
static SCOPED_MARKER: AtomicU64 = AtomicU64::new(1);

fn next_scoped_marker() -> u64 {
    SCOPED_MARKER.fetch_add(1, Ordering::Relaxed)
}

/// The fixed leading layout of a scoped userdata wrapper: a unique marker used
/// to recognise the instance (in place of a `TypeId`).
#[repr(C)]
struct ScopedHeader {
    marker: u64,
}

/// Scoped userdata storage: a unique marker followed by the data cell. Shares
/// `#[repr(C)]` with [`ScopedHeader`] so the marker is at offset 0 for any `T`.
#[repr(C)]
struct ScopedCell<T> {
    marker: u64,
    cell: RefCell<Option<T>>,
}

/// Destructor for the [`ScopedCell<T>`] stored inside a scoped userdata.
unsafe extern "C" fn scoped_userdata_dtor<T>(ptr: *mut c_void) {
    if !ptr.is_null() {
        unsafe { core::ptr::drop_in_place(ptr as *mut ScopedCell<T>) };
    }
}

/// Recover `&ScopedCell<T>` from a `self` userdata [`Value`] (Lua argument 1),
/// verifying the per-instance `marker`. A mismatch is an
/// [`Error::UserDataTypeMismatch`].
///
/// # Safety
/// The caller guarantees that any userdata carrying `marker` was created as a
/// `ScopedCell<T>` for this exact `T` (which holds because each marker is handed
/// out to exactly one `create_scoped_userdata::<T>` call).
unsafe fn recover_scoped_cell<'a, T>(
    lua: &Lua,
    value: &Value,
    marker: u64,
) -> Result<&'a ScopedCell<T>> {
    match value {
        Value::UserData(ud) => {
            let state = lua.state();
            unsafe {
                ud.reference.push();
                let ptr = lua_touserdata(state, -1);
                lua_pop(state, 1);
                if ptr.is_null() {
                    return Err(Error::UserDataTypeMismatch);
                }
                let header = &*(ptr as *const ScopedHeader);
                if header.marker != marker {
                    return Err(Error::UserDataTypeMismatch);
                }
                Ok(&*(ptr as *const ScopedCell<T>))
            }
        }
        _ => Err(Error::UserDataTypeMismatch),
    }
}

/// A concrete [`UserDataMethods`] / [`UserDataFields`] implementation for a
/// scoped (non-`'static`) userdata instance: identical surface to [`Collector`],
/// but it recovers the data cell by the per-instance `marker` rather than a
/// `TypeId`, so it works for non-`'static` `T`.
struct ScopedCollector<T> {
    marker: u64,
    methods: Vec<Registered>,
    fields: Vec<FieldEntry>,
    _phantom: PhantomData<T>,
}

impl<T> ScopedCollector<T> {
    fn new(marker: u64) -> Self {
        ScopedCollector {
            marker,
            methods: Vec::new(),
            fields: Vec::new(),
            _phantom: PhantomData,
        }
    }
}

impl<T> UserDataMethods<T> for ScopedCollector<T> {
    fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let marker = self.marker;
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
            let a = A::from_lua_multi(args, lua)?;
            let borrowed = cell
                .cell
                .try_borrow()
                .map_err(|_| Error::UserDataBorrowError)?;
            let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: false,
            callback,
        });
    }

    fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let marker = self.marker;
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
            let a = A::from_lua_multi(args, lua)?;
            let mut borrowed = cell
                .cell
                .try_borrow_mut()
                .map_err(|_| Error::UserDataBorrowMutError)?;
            let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: false,
            callback,
        });
    }

    fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let callback: BoxedCallback = Box::new(move |lua, args| {
            let a = A::from_lua_multi(args, lua)?;
            let r = function(lua, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: false,
            callback,
        });
    }

    fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let marker = self.marker;
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
            let a = A::from_lua_multi(args, lua)?;
            let borrowed = cell
                .cell
                .try_borrow()
                .map_err(|_| Error::UserDataBorrowError)?;
            let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: true,
            callback,
        });
    }

    fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
        A: FromLuaMulti,
        R: IntoLuaMulti,
    {
        let marker = self.marker;
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
            let a = A::from_lua_multi(args, lua)?;
            let mut borrowed = cell
                .cell
                .try_borrow_mut()
                .map_err(|_| Error::UserDataBorrowMutError)?;
            let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data, a)?;
            r.into_lua_multi(lua)
        });
        self.methods.push(Registered {
            name: name.into(),
            is_meta: true,
            callback,
        });
    }
}

impl<T> UserDataFields<T> for ScopedCollector<T> {
    fn add_field<V>(&mut self, name: impl Into<String>, value: V)
    where
        V: IntoLua + Clone + MaybeSend + 'static,
    {
        let callback: BoxedCallback = Box::new(move |lua, _args| {
            let v = value.clone().into_lua(lua)?;
            v.into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: true,
            callback,
        });
    }

    fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
        R: IntoLua,
    {
        let marker = self.marker;
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
            let borrowed = cell
                .cell
                .try_borrow()
                .map_err(|_| Error::UserDataBorrowError)?;
            let data = borrowed.as_ref().ok_or(Error::UserDataDestructed)?;
            let r = method(lua, data)?;
            r.into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: true,
            callback,
        });
    }

    fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
    where
        M: Fn(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
        A: FromLua,
    {
        let marker = self.marker;
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let cell = unsafe { recover_scoped_cell::<T>(lua, &this, marker)? };
            let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
            let mut borrowed = cell
                .cell
                .try_borrow_mut()
                .map_err(|_| Error::UserDataBorrowMutError)?;
            let data = borrowed.as_mut().ok_or(Error::UserDataDestructed)?;
            method(lua, data, val)?;
            ().into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: false,
            callback,
        });
    }

    fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
        R: IntoLua,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let ud = AnyUserData::from_lua(this, lua)?;
            let r = function(lua, ud)?;
            r.into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: true,
            callback,
        });
    }

    fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
        A: FromLua,
    {
        let callback: BoxedCallback = Box::new(move |lua, mut args| {
            let this = args.pop_front().unwrap_or(Value::Nil);
            let ud = AnyUserData::from_lua(this, lua)?;
            let val = A::from_lua(args.pop_front().unwrap_or(Value::Nil), lua)?;
            function(lua, ud, val)?;
            ().into_lua_multi(lua)
        });
        self.fields.push(FieldEntry {
            name: name.into(),
            is_get: false,
            callback,
        });
    }
}

/// Build a scoped (non-`'static`) userdata wrapping `data`, with a metatable
/// assembled from `T::add_fields` + `T::add_methods`. Returns the
/// [`AnyUserData`] handle plus a closure that, when called, neutralises the
/// userdata (drops `data`, leaving later access to error with
/// [`Error::UserDataDestructed`]). The neutraliser is what `Lua::scope`
/// registers as a destructor.
///
/// # Safety
/// The returned [`AnyUserData`] must not be used to read `data` back out by
/// type (there is no `TypeId`); only metatable-driven method/field/meta dispatch
/// is supported. The scope must invoke the returned neutraliser before `data`'s
/// borrowed lifetime ends.
pub(crate) fn create_scoped_userdata<T: UserData>(
    lua: &Lua,
    data: T,
) -> Result<(AnyUserData, Box<dyn FnOnce()>)> {
    let state = lua.state();
    let marker = next_scoped_marker();

    // 1. Collect fields, methods, and meta-methods (marker-keyed recovery).
    let mut collector = ScopedCollector::<T>::new(marker);
    T::add_fields(&mut collector);
    T::add_methods(&mut collector);

    // 2. Build the method table + meta-methods + field getter/setter tables.
    let method_table = lua.create_table();
    let metatable = lua.create_table();
    for item in collector.methods {
        let func = create_callback_function(lua, item.callback)?;
        if item.is_meta {
            metatable.set(item.name, func)?;
        } else {
            method_table.set(item.name, func)?;
        }
    }

    let has_fields = !collector.fields.is_empty();
    let getters = lua.create_table();
    let setters = lua.create_table();
    for field in collector.fields {
        let func = create_callback_function(lua, field.callback)?;
        if field.is_get {
            getters.set(field.name, func)?;
        } else {
            setters.set(field.name, func)?;
        }
    }

    if has_fields {
        let getters_c = getters.clone();
        let methods_c = method_table.clone();
        let index_fn = lua.create_function(move |_, (ud, key): (Value, Value)| {
            let getter: Value = getters_c.get(key.clone())?;
            if let Value::Function(f) = getter {
                return f.call::<Value>(ud);
            }
            let m: Value = methods_c.get(key)?;
            Ok(m)
        })?;
        metatable.set("__index", index_fn)?;

        let setters_c = setters.clone();
        let newindex_fn =
            lua.create_function(move |_, (ud, key, val): (Value, Value, Value)| {
                let setter: Value = setters_c.get(key.clone())?;
                if let Value::Function(f) = setter {
                    f.call::<()>((ud, val))?;
                    return Ok(());
                }
                let name = key.to_string().unwrap_or_default();
                Err(Error::RuntimeError(format!(
                    "attempt to set unknown field '{name}' on userdata"
                )))
            })?;
        metatable.set("__newindex", newindex_fn)?;
    } else {
        metatable.set("__index", method_table)?;
    }

    // 3. Allocate the scoped userdata holding ScopedCell<T> and move `data` in.
    let ud = unsafe {
        let storage = lua_newuserdatadtor(
            state,
            core::mem::size_of::<ScopedCell<T>>(),
            Some(scoped_userdata_dtor::<T>),
        );
        if storage.is_null() {
            return Err(Error::runtime(
                "luaur-rt: failed to allocate scoped userdata",
            ));
        }
        core::ptr::write(
            storage as *mut ScopedCell<T>,
            ScopedCell {
                marker,
                cell: RefCell::new(Some(data)),
            },
        );
        metatable.push_to_stack();
        lua_setmetatable(state, -2);
        AnyUserData::from_ref(lua.pop_ref())
    };

    // 4. Build the neutraliser: on scope exit, take the data out of the cell,
    //    dropping the (possibly borrowing) `T` while the cell memory stays valid.
    let ud_for_dtor = ud.clone();
    let neutralise: Box<dyn FnOnce()> = Box::new(move || {
        let state = ud_for_dtor.reference.state();
        unsafe {
            ud_for_dtor.reference.push();
            let ptr = lua_touserdata(state, -1);
            lua_pop(state, 1);
            if ptr.is_null() {
                return;
            }
            let cell = &*(ptr as *const ScopedCell<T>);
            // Drop the data (ends borrows). If currently borrowed (a method is
            // somehow live), `try_borrow_mut` fails and we leave it — but scope
            // exit only happens after `f` returns, so no method is in flight.
            if let Ok(mut guard) = cell.cell.try_borrow_mut() {
                let _ = guard.take();
            }
        }
    });

    Ok((ud, neutralise))
}

/// Build a userdata value wrapping `data`, with a metatable assembled from the
/// type's [`UserData::add_fields`] + [`UserData::add_methods`].
pub(crate) fn create_userdata<T: UserData + MaybeSend + MaybeSync + 'static>(
    lua: &Lua,
    data: T,
) -> Result<AnyUserData> {
    let state = lua.state();

    // 1. Collect fields, methods, and meta-methods.
    let mut collector = Collector::<T>::new();
    T::add_fields(&mut collector);
    T::add_methods(&mut collector);

    // 2. Build the method table + meta-methods, and the field getter/setter
    //    tables (if any fields were registered).
    let method_table = lua.create_table();
    let metatable = lua.create_table();
    for item in collector.methods {
        let func = create_callback_function(lua, item.callback)?;
        if item.is_meta {
            metatable.set(item.name, func)?;
        } else {
            method_table.set(item.name, func)?;
        }
    }

    let has_fields = !collector.fields.is_empty();
    let getters = lua.create_table();
    let setters = lua.create_table();
    for field in collector.fields {
        let func = create_callback_function(lua, field.callback)?;
        if field.is_get {
            getters.set(field.name, func)?;
        } else {
            setters.set(field.name, func)?;
        }
    }

    if has_fields {
        // __index dispatcher: try a field getter, then the method table.
        let getters_c = getters.clone();
        let methods_c = method_table.clone();
        let index_fn = lua.create_function(move |_, (ud, key): (Value, Value)| {
            let getter: Value = getters_c.get(key.clone())?;
            if let Value::Function(f) = getter {
                return f.call::<Value>(ud);
            }
            // Fall back to the method table.
            let m: Value = methods_c.get(key)?;
            Ok(m)
        })?;
        metatable.set("__index", index_fn)?;

        // __newindex dispatcher: try a field setter, else raise.
        let setters_c = setters.clone();
        let newindex_fn =
            lua.create_function(move |_, (ud, key, val): (Value, Value, Value)| {
                let setter: Value = setters_c.get(key.clone())?;
                if let Value::Function(f) = setter {
                    f.call::<()>((ud, val))?;
                    return Ok(());
                }
                let name = key.to_string().unwrap_or_default();
                Err(Error::RuntimeError(format!(
                    "attempt to set unknown field '{name}' on userdata"
                )))
            })?;
        metatable.set("__newindex", newindex_fn)?;
    } else {
        // No fields: the metatable's __index is just the method table.
        metatable.set("__index", method_table)?;
    }

    // 3. Allocate the userdata holding UserDataCell<T> and move `data` in.
    unsafe {
        let storage = lua_newuserdatadtor(
            state,
            core::mem::size_of::<UserDataCell<T>>(),
            Some(userdata_dtor::<T>),
        );
        if storage.is_null() {
            return Err(Error::runtime("luaur-rt: failed to allocate userdata"));
        }
        core::ptr::write(
            storage as *mut UserDataCell<T>,
            UserDataCell {
                type_id: TypeId::of::<T>(),
                cell: RefCell::new(Some(data)),
            },
        );

        // 4. Set the metatable on the userdata (which is on top of stack).
        metatable.push_to_stack();
        lua_setmetatable(state, -2);

        // 5. Take a ref to the userdata and return.
        Ok(AnyUserData::from_ref(lua.pop_ref()))
    }
}