Skip to main content

lua_types/
userdata.rs

1//! `LuaUserData` — Lua's heap-allocated userdata. Carries a typed byte
2//! buffer plus optional user values (a Vec of TValues).
3
4use std::any::Any;
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use crate::gc::GcRef;
9use crate::table::LuaTable;
10use crate::value::LuaValue;
11
12pub struct LuaUserData {
13    pub data: Box<[u8]>,
14    pub uv: Vec<LuaValue>,
15    pub metatable: RefCell<Option<GcRef<LuaTable>>>,
16    pub host_value: RefCell<Option<Rc<dyn Any>>>,
17}
18
19impl std::fmt::Debug for LuaUserData {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        f.debug_struct("LuaUserData")
22            .field("data_len", &self.data.len())
23            .field("uv_len", &self.uv.len())
24            .field("has_metatable", &self.metatable.borrow().is_some())
25            .field("has_host_value", &self.host_value.borrow().is_some())
26            .finish()
27    }
28}
29
30impl LuaUserData {
31    pub fn placeholder() -> Self {
32        LuaUserData {
33            data: Box::new([]),
34            uv: Vec::new(),
35            metatable: RefCell::new(None),
36            host_value: RefCell::new(None),
37        }
38    }
39
40    pub fn metatable(&self) -> Option<GcRef<LuaTable>> {
41        self.metatable.borrow().clone()
42    }
43
44    pub fn set_metatable(&self, mt: Option<GcRef<LuaTable>>) {
45        *self.metatable.borrow_mut() = mt;
46    }
47
48    pub fn host_value(&self) -> Option<Rc<dyn Any>> {
49        self.host_value.borrow().clone()
50    }
51
52    pub fn set_host_value(&self, value: Option<Rc<dyn Any>>) {
53        *self.host_value.borrow_mut() = value;
54    }
55}
56
57// ──────────────────────────────────────────────────────────────────────────────
58// PORT STATUS
59//   source:        src/lobject.h (Udata + Udata0)
60//   target_crate:  lua-types
61//   confidence:    high
62//   todos:         0
63//   port_notes:    0
64//   unsafe_blocks: 0
65//   notes:         LuaUserData type, including metatable slot and uservalues. C uses a
66//                  flexible-array trailing payload; we use a typed Vec / Box of the
67//                  user payload + uservalues vector.
68// ──────────────────────────────────────────────────────────────────────────────