Skip to main content

luaur_rt/
table.rs

1//! The [`Table`] handle. Mirrors `mlua::Table`.
2
3use crate::error::Result;
4use crate::state::{Lua, LuaRef};
5use crate::sync::{NotSync, XRc, NOT_SYNC};
6use crate::sys::*;
7use crate::traits::{FromLua, IntoLua};
8use crate::value::Value;
9
10/// A handle to a Lua table.
11///
12/// Mirrors `mlua::Table`. Holds a registry reference keeping the table alive.
13///
14/// Under the `send` feature this handle is `Send` (the VM can be moved across
15/// threads) but never `Sync` — see [`crate::sync::NotSync`].
16#[derive(Clone)]
17pub struct Table {
18    pub(crate) reference: XRc<LuaRef>,
19    pub(crate) _not_sync: NotSync,
20}
21
22/// Reserve `slots` stack slots for a raw table operation.
23///
24/// `lua_checkstack` raises the stack top inside the current call-info frame;
25/// without it, `lua_pushvalue` (and the extra copy `value_from_stack` pushes
26/// for reference types) can trip the `top < ci.top` LUAU_ASSERT and abort the
27/// process when the caller's stack margin is already thin (for example after
28/// a long sequence of VM operations in the same frame).
29pub(crate) fn ensure_stack(state: *mut lua_State, slots: c_int) -> Result<()> {
30    if unsafe { lua_checkstack(state, slots) } == 0 {
31        // Same shape as the guards in `Function::call` / `Thread::resume`:
32        // a catchable `RuntimeError` rather than a VM abort.
33        return Err(crate::error::Error::RuntimeError(
34            "stack overflow: not enough stack space for a raw table operation".to_string(),
35        ));
36    }
37    Ok(())
38}
39
40impl Table {
41    pub(crate) fn from_ref(reference: LuaRef) -> Table {
42        Table {
43            reference: XRc::new(reference),
44            _not_sync: NOT_SYNC,
45        }
46    }
47
48    pub(crate) unsafe fn push_to_stack(&self) {
49        self.reference.push();
50    }
51
52    /// The owning [`Lua`].
53    pub fn lua(&self) -> Lua {
54        self.reference.lua()
55    }
56
57    /// Set `table[key] = value`, honoring metamethods (`__newindex`).
58    ///
59    /// Mirrors `mlua::Table::set`. Errors (`RuntimeError`) propagate from a
60    /// `__newindex` metamethod that raises.
61    pub fn set<K: IntoLua, V: IntoLua>(&self, key: K, value: V) -> Result<()> {
62        let lua = self.lua();
63        let state = lua.state();
64        let k = key.into_lua(&lua)?;
65        let v = value.into_lua(&lua)?;
66        // Drive the (possibly metamethod-invoking) settable under pcall so a
67        // raising `__newindex` (or readonly table) surfaces as `Err`.
68        unsafe {
69            self.reference.push(); // table
70            lua.push_value(&k)?; // key
71            lua.push_value(&v)?; // value
72            let status = protected_settable(state);
73            if status != 0 {
74                return Err(lua.pop_error(status));
75            }
76        }
77        Ok(())
78    }
79
80    /// Get `table[key]`, honoring metamethods (`__index`), converting the
81    /// result to `V`.
82    ///
83    /// Mirrors `mlua::Table::get`. The value type is the sole explicit type
84    /// parameter (key type is inferred), matching mlua's `get::<V>(key)`.
85    pub fn get<V: FromLua>(&self, key: impl IntoLua) -> Result<V> {
86        let lua = self.lua();
87        let state = lua.state();
88        let k = key.into_lua(&lua)?;
89        let value = unsafe {
90            self.reference.push(); // table
91            lua.push_value(&k)?; // key
92            let status = protected_gettable(state);
93            if status != 0 {
94                return Err(lua.pop_error(status));
95            }
96            let v = lua.value_from_stack(-1)?;
97            lua_pop(state, 1); // pop the result value
98            v
99        };
100        V::from_lua(value, &lua)
101    }
102
103    /// Whether `table[key]` is non-nil.
104    ///
105    /// Mirrors `mlua::Table::contains_key`.
106    pub fn contains_key<K: IntoLua>(&self, key: K) -> Result<bool> {
107        let v: Value = self.get(key)?;
108        Ok(!v.is_nil())
109    }
110
111    /// The border length (`#table`).
112    ///
113    /// Mirrors `mlua::Table::raw_len` (returns `usize`). luaur's `lua_objlen`
114    /// gives the same border-length semantics as `lua_rawlen`.
115    pub fn raw_len(&self) -> usize {
116        let state = self.reference.state();
117        unsafe {
118            self.reference.push();
119            let n = lua_objlen(state, -1);
120            lua_pop(state, 1);
121            n.max(0) as usize
122        }
123    }
124
125    /// The length (`#table`), honoring a `__len` metamethod.
126    ///
127    /// Mirrors `mlua::Table::len`. Returns `Err` if a `__len` metamethod
128    /// raises. Without a `__len` metamethod this is the raw border length.
129    pub fn len(&self) -> Result<usize> {
130        let lua = self.lua();
131        // Fast path: no metatable -> raw border length (no metamethod possible).
132        if self.metatable().is_none() {
133            return Ok(self.raw_len());
134        }
135        // Evaluate `#self` protected so a raising/returning `__len` is honored.
136        let f = lua.load("local t = ...; return #t").into_function()?;
137        let n: i64 = f.call(self.clone())?;
138        Ok(n.max(0) as usize)
139    }
140
141    /// Whether the table is empty, without invoking metamethods.
142    ///
143    /// Mirrors `mlua::Table::is_empty`: checks **both** the array part and the
144    /// hash part (a table with only string keys is *not* empty). Uses a single
145    /// `lua_next` probe — present iff the table has at least one key.
146    pub fn is_empty(&self) -> bool {
147        let state = self.reference.state();
148        unsafe {
149            self.reference.push(); // table
150            lua_pushnil(state); // first key
151            if lua_next(state, -2) == 0 {
152                // No first key: table is empty. `lua_next` already popped the key.
153                lua_pop(state, 1); // pop table
154                return true;
155            }
156            // stack: table, key, value — pop value+key+table.
157            lua_pop(state, 3);
158            false
159        }
160    }
161
162    /// Iterate over `(key, value)` pairs.
163    ///
164    /// Mirrors `mlua::Table::pairs`. Returns an iterator yielding `Result<(K,
165    /// V)>` items. Uses `lua_next` under the hood.
166    pub fn pairs<K: FromLua, V: FromLua>(&self) -> TablePairs<K, V> {
167        TablePairs {
168            table: self.clone(),
169            next_key: Some(Value::Nil),
170            _phantom: std::marker::PhantomData,
171        }
172    }
173
174    /// Collect all `(key, value)` pairs into a `Vec`. Convenience over
175    /// [`Table::pairs`].
176    pub fn pairs_vec<K: FromLua, V: FromLua>(&self) -> Result<Vec<(K, V)>> {
177        self.pairs().collect()
178    }
179
180    /// Iterate over the sequence part `[1..]`, stopping at the first `nil`
181    /// (raw access — ignores `__index`). Mirrors `mlua::Table::sequence_values`.
182    pub fn sequence_values<V: FromLua>(&self) -> TableSequence<V> {
183        TableSequence {
184            table: self.clone(),
185            index: 1,
186            _phantom: std::marker::PhantomData,
187        }
188    }
189
190    /// Call `f` for each `(key, value)` pair (raw `lua_next` traversal).
191    /// Stops early on the first `Err`. Mirrors `mlua::Table::for_each`.
192    ///
193    /// The key/value types are the only explicit type parameters (the closure
194    /// type is inferred), matching mlua's `for_each::<K, V>(f)`.
195    pub fn for_each<K: FromLua, V: FromLua>(
196        &self,
197        mut f: impl FnMut(K, V) -> Result<()>,
198    ) -> Result<()> {
199        for pair in self.pairs::<K, V>() {
200            let (k, v) = pair?;
201            f(k, v)?;
202        }
203        Ok(())
204    }
205
206    /// Call `f` for each value in the sequence part. Mirrors
207    /// `mlua::Table::for_each_value`.
208    pub fn for_each_value<V: FromLua>(&self, mut f: impl FnMut(V) -> Result<()>) -> Result<()> {
209        for v in self.sequence_values::<V>() {
210            f(v?)?;
211        }
212        Ok(())
213    }
214
215    // --- raw (metamethod-bypassing) access ---------------------------------
216
217    /// Set `table[key] = value` without invoking `__newindex`.
218    ///
219    /// Mirrors `mlua::Table::raw_set`. Errors if the table is readonly.
220    pub fn raw_set<K: IntoLua, V: IntoLua>(&self, key: K, value: V) -> Result<()> {
221        let lua = self.lua();
222        let state = lua.state();
223        let k = key.into_lua(&lua)?;
224        let v = value.into_lua(&lua)?;
225        if self.is_readonly() {
226            return Err(crate::error::Error::RuntimeError(
227                "attempt to modify a readonly table".to_string(),
228            ));
229        }
230        ensure_stack(state, 3)?;
231        unsafe {
232            self.reference.push(); // table
233            lua.push_value(&k)?; // key
234            lua.push_value(&v)?; // value
235            lua_rawset(state, -3);
236            lua_pop(state, 1); // pop table
237        }
238        Ok(())
239    }
240
241    /// Get `table[key]` without invoking `__index`.
242    ///
243    /// Mirrors `mlua::Table::raw_get`.
244    pub fn raw_get<V: FromLua>(&self, key: impl IntoLua) -> Result<V> {
245        let lua = self.lua();
246        let state = lua.state();
247        let k = key.into_lua(&lua)?;
248        ensure_stack(state, 3)?;
249        let value = unsafe {
250            self.reference.push(); // table
251            lua.push_value(&k)?; // key
252            lua_rawget(state, -2); // replaces key with value
253            let v = lua.value_from_stack(-1)?;
254            lua_pop(state, 2); // pop value + table
255            v
256        };
257        V::from_lua(value, &lua)
258    }
259
260    /// Append `value` at position `#table + 1` using raw access.
261    ///
262    /// Mirrors `mlua::Table::raw_push`. Errors if readonly.
263    pub fn raw_push<V: IntoLua>(&self, value: V) -> Result<()> {
264        let n = self.raw_len();
265        self.raw_set((n + 1) as i64, value)
266    }
267
268    /// Remove and return the last sequence element via raw access.
269    ///
270    /// Mirrors `mlua::Table::raw_pop`. Errors if readonly.
271    pub fn raw_pop<V: FromLua>(&self) -> Result<V> {
272        let lua = self.lua();
273        let n = self.raw_len();
274        if n == 0 {
275            return V::from_lua(Value::Nil, &lua);
276        }
277        if self.is_readonly() {
278            return Err(crate::error::Error::RuntimeError(
279                "attempt to modify a readonly table".to_string(),
280            ));
281        }
282        let v: V = self.raw_get(n as i64)?;
283        self.raw_set(n as i64, Value::Nil)?;
284        Ok(v)
285    }
286
287    /// Insert `value` at 1-based `idx`, shifting later elements up (raw).
288    ///
289    /// Mirrors `mlua::Table::raw_insert`. Errors on bad index or readonly.
290    pub fn raw_insert<V: IntoLua>(&self, idx: i64, value: V) -> Result<()> {
291        let n = self.raw_len() as i64;
292        if idx < 1 || idx > n + 1 {
293            return Err(crate::error::Error::RuntimeError(format!(
294                "bad argument #2 to 'insert' (position out of bounds): {idx}"
295            )));
296        }
297        if self.is_readonly() {
298            return Err(crate::error::Error::RuntimeError(
299                "attempt to modify a readonly table".to_string(),
300            ));
301        }
302        // Shift [idx..=n] up by one, then place the new value.
303        let mut i = n;
304        while i >= idx {
305            let moved: Value = self.raw_get(i)?;
306            self.raw_set(i + 1, moved)?;
307            i -= 1;
308        }
309        self.raw_set(idx, value.into_lua(&self.lua())?)
310    }
311
312    /// Remove and return the element at 1-based `idx`, shifting later
313    /// elements down (raw). Mirrors `mlua::Table::raw_remove`.
314    pub fn raw_remove(&self, idx: i64) -> Result<Value> {
315        let n = self.raw_len() as i64;
316        if n == 0 {
317            return Ok(Value::Nil);
318        }
319        if idx < 1 || idx > n {
320            return Err(crate::error::Error::RuntimeError(format!(
321                "bad argument #1 to 'remove' (position out of bounds): {idx}"
322            )));
323        }
324        if self.is_readonly() {
325            return Err(crate::error::Error::RuntimeError(
326                "attempt to modify a readonly table".to_string(),
327            ));
328        }
329        let removed: Value = self.raw_get(idx)?;
330        let mut i = idx;
331        while i < n {
332            let moved: Value = self.raw_get(i + 1)?;
333            self.raw_set(i, moved)?;
334            i += 1;
335        }
336        self.raw_set(n, Value::Nil)?;
337        Ok(removed)
338    }
339
340    /// Append `value` honoring `__len`/`__newindex` (uses `#self + 1`).
341    /// Mirrors `mlua::Table::push`.
342    pub fn push<V: IntoLua>(&self, value: V) -> Result<()> {
343        let n = self.len()?;
344        self.set((n + 1) as i64, value)
345    }
346
347    /// Pop the last element honoring `__len`/`__index`/`__newindex`.
348    /// Mirrors `mlua::Table::pop`.
349    pub fn pop<V: FromLua>(&self) -> Result<V> {
350        let lua = self.lua();
351        let n = self.len()?;
352        if n == 0 {
353            return V::from_lua(Value::Nil, &lua);
354        }
355        let v: V = self.get(n as i64)?;
356        self.set(n as i64, Value::Nil)?;
357        Ok(v)
358    }
359
360    /// Remove all keys from the table (raw). Errors if readonly.
361    /// Mirrors `mlua::Table::clear`.
362    pub fn clear(&self) -> Result<()> {
363        if self.is_readonly() {
364            return Err(crate::error::Error::RuntimeError(
365                "attempt to modify a readonly table".to_string(),
366            ));
367        }
368        // Collect every key (raw traversal), then nil them out.
369        let lua = self.lua();
370        let state = lua.state();
371        let mut keys: Vec<Value> = Vec::new();
372        unsafe {
373            self.reference.push(); // table
374            lua_pushnil(state); // first key
375            while lua_next(state, -2) != 0 {
376                // stack: table, key, value
377                let k = lua.value_from_stack(-2)?;
378                keys.push(k);
379                lua_pop(state, 1); // pop value, keep key for next iteration
380            }
381            lua_pop(state, 1); // pop table
382        }
383        for k in keys {
384            self.raw_set(k, Value::Nil)?;
385        }
386        Ok(())
387    }
388
389    // --- identity / equality / metatables ----------------------------------
390
391    /// A raw pointer identifying this table (for identity comparison).
392    /// Mirrors `mlua::Table::to_pointer`.
393    pub fn to_pointer(&self) -> *const std::ffi::c_void {
394        let state = self.reference.state();
395        unsafe {
396            self.reference.push();
397            let p = lua_topointer(state, -1);
398            lua_pop(state, 1);
399            p
400        }
401    }
402
403    /// Compare for equality honoring an `__eq` metamethod.
404    /// Mirrors `mlua::Table::equals`.
405    pub fn equals(&self, other: &Table) -> Result<bool> {
406        let lua = self.lua();
407        let state = lua.state();
408        unsafe {
409            self.reference.push();
410            other.reference.push();
411            let eq = lua_equal(state, -2, -1);
412            lua_pop(state, 2);
413            Ok(eq != 0)
414        }
415    }
416
417    /// The table's metatable, if any. Mirrors `mlua::Table::metatable`.
418    pub fn metatable(&self) -> Option<Table> {
419        let lua = self.lua();
420        let state = lua.state();
421        unsafe {
422            self.reference.push();
423            let has = lua_getmetatable(state, -1);
424            if has == 0 {
425                lua_pop(state, 1); // pop table
426                return None;
427            }
428            // stack: table, metatable
429            let mt = Table::from_ref(lua.pop_ref());
430            lua_pop(state, 1); // pop table
431            Some(mt)
432        }
433    }
434
435    /// Set (or clear, with `None`) the table's metatable.
436    /// Mirrors `mlua::Table::set_metatable`. Errors if the table is readonly.
437    pub fn set_metatable(&self, metatable: Option<Table>) -> Result<()> {
438        if self.is_readonly() {
439            return Err(crate::error::Error::RuntimeError(
440                "attempt to modify a readonly table".to_string(),
441            ));
442        }
443        let lua = self.lua();
444        let state = lua.state();
445        unsafe {
446            self.reference.push(); // table
447            match metatable {
448                Some(mt) => mt.push_to_stack(),
449                None => lua_pushnil(state),
450            }
451            lua_setmetatable(state, -2);
452            lua_pop(state, 1); // pop table
453        }
454        Ok(())
455    }
456
457    // --- readonly (Luau extension) -----------------------------------------
458
459    /// Whether the table is marked readonly (Luau). Mirrors
460    /// `mlua::Table::is_readonly`.
461    pub fn is_readonly(&self) -> bool {
462        let state = self.reference.state();
463        unsafe {
464            self.reference.push();
465            let ro = lua_getreadonly(state, -1);
466            lua_pop(state, 1);
467            ro != 0
468        }
469    }
470
471    /// Mark the table readonly or writable (Luau). Mirrors
472    /// `mlua::Table::set_readonly`.
473    pub fn set_readonly(&self, enabled: bool) {
474        let state = self.reference.state();
475        unsafe {
476            self.reference.push();
477            lua_setreadonly(state, -1, enabled as c_int);
478            lua_pop(state, 1);
479        }
480    }
481}
482
483/// Iterator over a table's sequence part (see [`Table::sequence_values`]).
484pub struct TableSequence<V> {
485    table: Table,
486    index: i64,
487    _phantom: std::marker::PhantomData<V>,
488}
489
490impl<V: FromLua> Iterator for TableSequence<V> {
491    type Item = Result<V>;
492
493    fn next(&mut self) -> Option<Self::Item> {
494        let lua = self.table.lua();
495        // Raw get of the next sequence slot; stop at the first nil.
496        let value: Value = match self.table.raw_get(self.index) {
497            Ok(v) => v,
498            Err(e) => return Some(Err(e)),
499        };
500        if value.is_nil() {
501            return None;
502        }
503        self.index += 1;
504        Some(V::from_lua(value, &lua))
505    }
506}
507
508impl std::fmt::Debug for Table {
509    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510        write!(f, "Table(len={})", self.raw_len())
511    }
512}
513
514impl PartialEq for Table {
515    fn eq(&self, other: &Self) -> bool {
516        // Reference (pointer) identity, matching mlua's `==` on handles: two
517        // handles are equal iff they point at the *same* Lua table object.
518        self.to_pointer() == other.to_pointer()
519    }
520}
521
522/// Compare a [`Table`]'s sequence part to a Rust slice of values.
523///
524/// Mirrors mlua's `impl PartialEq<[T]> for Table`: equal when the table's
525/// `1..=len` sequence (read raw) matches `other` element-wise and has the
526/// same length.
527impl<T> PartialEq<[T]> for Table
528where
529    T: FromLua + PartialEq + Clone,
530{
531    fn eq(&self, other: &[T]) -> bool {
532        // Compare the *sequence* part (stopping at the first nil border),
533        // matching mlua's `sequence_values`-based slice comparison. This is the
534        // robust border semantics for tables with nil holes (e.g.
535        // `{1, 2, nil, 4, 5}` compares equal to `[1, 2]`).
536        let mut iter = self.sequence_values::<T>();
537        for expected in other.iter() {
538            match iter.next() {
539                Some(Ok(got)) if &got == expected => {}
540                _ => return false,
541            }
542        }
543        // The sequence must be exactly the slice length (no extra elements).
544        iter.next().is_none()
545    }
546}
547
548impl<T, const N: usize> PartialEq<[T; N]> for Table
549where
550    T: FromLua + PartialEq + Clone,
551{
552    fn eq(&self, other: &[T; N]) -> bool {
553        self == other.as_slice()
554    }
555}
556
557impl<T> PartialEq<&[T]> for Table
558where
559    T: FromLua + PartialEq + Clone,
560{
561    fn eq(&self, other: &&[T]) -> bool {
562        self == *other
563    }
564}
565
566/// Iterator over a table's key/value pairs (see [`Table::pairs`]).
567pub struct TablePairs<K, V> {
568    table: Table,
569    next_key: Option<Value>,
570    _phantom: std::marker::PhantomData<(K, V)>,
571}
572
573impl<K: FromLua, V: FromLua> Iterator for TablePairs<K, V> {
574    type Item = Result<(K, V)>;
575
576    fn next(&mut self) -> Option<Self::Item> {
577        let key = self.next_key.take()?;
578        let lua = self.table.lua();
579        let state = lua.state();
580        unsafe {
581            self.table.reference.push(); // [.. table]
582            if lua.push_value(&key).is_err() {
583                lua_pop(state, 1);
584                return None;
585            }
586            // stack: [table, key]
587            let has = lua_next(state, -2);
588            if has == 0 {
589                // lua_next popped the key; pop the table.
590                lua_pop(state, 1);
591                self.next_key = None;
592                return None;
593            }
594            // stack: [table, next_key, value]
595            let k_val = match lua.value_from_stack(-2) {
596                Ok(v) => v,
597                Err(e) => {
598                    lua_pop(state, 3);
599                    return Some(Err(e));
600                }
601            };
602            let v_val = match lua.value_from_stack(-1) {
603                Ok(v) => v,
604                Err(e) => {
605                    lua_pop(state, 3);
606                    return Some(Err(e));
607                }
608            };
609            // Remember the key for the next iteration, then clean the stack.
610            self.next_key = Some(k_val.clone());
611            lua_pop(state, 3); // value, next_key, table
612
613            let k = match K::from_lua(k_val, &lua) {
614                Ok(k) => k,
615                Err(e) => return Some(Err(e)),
616            };
617            let v = match V::from_lua(v_val, &lua) {
618                Ok(v) => v,
619                Err(e) => return Some(Err(e)),
620            };
621            Some(Ok((k, v)))
622        }
623    }
624}
625
626/// Create a fresh empty table on `lua` and return a handle.
627pub(crate) fn create_table(lua: &Lua) -> Table {
628    let state = lua.state();
629    unsafe {
630        lua_createtable(state, 0, 0);
631        Table::from_ref(lua.pop_ref())
632    }
633}
634
635// ---------------------------------------------------------------------------
636// Protected indexing
637//
638// `lua_gettable`/`lua_settable` may invoke `__index`/`__newindex` metamethods
639// that *raise* (longjmp). Calling them unprotected across the Rust/VM boundary
640// would unwind past Rust frames. We therefore run them inside `lua_pcall` via a
641// tiny C trampoline, so a raising metamethod (or a readonly-table write) is
642// reported as an ordinary non-zero status with the error object on the stack.
643// ---------------------------------------------------------------------------
644
645/// C trampoline: stack is `[table, key]`; performs `lua_gettable` and leaves
646/// the result on top.
647unsafe fn c_gettable(state: *mut lua_State) -> c_int {
648    unsafe {
649        lua_gettable(state, 1);
650        1
651    }
652}
653
654/// C trampoline: stack is `[table, key, value]`; performs `lua_settable`.
655unsafe fn c_settable(state: *mut lua_State) -> c_int {
656    unsafe {
657        lua_settable(state, 1);
658        0
659    }
660}
661
662/// Run `lua_gettable` protected. Expects `[table, key]` on top; on success
663/// leaves `[result]` where the two inputs were; on failure leaves the error
664/// object on top and returns the non-zero status.
665unsafe fn protected_gettable(state: *mut lua_State) -> c_int {
666    unsafe {
667        // Insert the C function below the two arguments: [t, k] -> [f, t, k].
668        lua_pushcclosurek(
669            state,
670            Some(c_gettable),
671            c"luaur-rt-gettable".as_ptr(),
672            0,
673            None,
674        );
675        lua_insert(state, -3);
676        lua_pcall(state, 2, 1, 0)
677    }
678}
679
680/// Run `lua_settable` protected. Expects `[table, key, value]` on top; pops
681/// them on success; on failure leaves the error object and returns the status.
682unsafe fn protected_settable(state: *mut lua_State) -> c_int {
683    unsafe {
684        // [t, k, v] -> [f, t, k, v].
685        lua_pushcclosurek(
686            state,
687            Some(c_settable),
688            c"luaur-rt-settable".as_ptr(),
689            0,
690            None,
691        );
692        lua_insert(state, -4);
693        lua_pcall(state, 3, 0, 0)
694    }
695}