lua_stdlib/table_lib.rs
1//! Lua `table` standard library.
2//!
3//! Provides: `table.concat`, `table.insert`, `table.move`, `table.pack`,
4//! `table.remove`, `table.sort`, `table.unpack`.
5//!
6//! C source: `reference/lua-5.4.7/src/ltablib.c`.
7
8use crate::state_stub::{CompareOp, LuaState, LuaStateStubExt as _};
9use lua_types::{GcRef, LuaError, LuaTable, LuaType, LuaValue};
10use lua_vm::state::LuaTableRefExt as _;
11
12// ─── Operation flags ──────────────────────────────────────────────────────────
13const TAB_R: u32 = 1;
14const TAB_W: u32 = 2;
15const TAB_L: u32 = 4;
16const TAB_RW: u32 = TAB_R | TAB_W;
17
18const RANLIMIT: u32 = 100;
19
20type IdxT = u32;
21
22// ─── Internal helpers ─────────────────────────────────────────────────────────
23
24/// Raw-gets `key` from the table currently sitting at stack depth `n` (a
25/// metatable, in practice); returns `true` if the looked-up value is not nil.
26/// Pushes `key`, then `raw_get(-n)` replaces it with the result in place.
27fn check_field(state: &mut LuaState, key: &[u8], n: i32) -> Result<bool, LuaError> {
28 state.push_string(key)?;
29 // raw_get(-n): looks up MT[key] (MT is at -n after the key push), replaces key with value
30 let ty = state.raw_get(-n)?;
31 Ok(ty != LuaType::Nil)
32}
33
34/// Accepts `arg` if it is a table, or a non-table that carries a metatable with
35/// every metamethod `what` requires (`TAB_R` → `__index`, `TAB_W` →
36/// `__newindex`, `TAB_L` → `__len`). The fields are checked left-to-right and
37/// short-circuit: a missing field stops the scan and falls through to the
38/// table-type error. Otherwise raises "table expected".
39///
40/// DEFERRED (behaviorally inert): on the failure path the metatable and any
41/// field values pushed during the scan are not popped before raising. In C the
42/// `longjmp` unwinds them; here the `LuaError` propagates and the call frame is
43/// torn down, so no observable behavior differs — but the stack is left dirty
44/// on that path. A tidy fix would pop `n` before `check_arg_type`.
45fn check_tab(state: &mut LuaState, arg: i32, what: u32) -> Result<(), LuaError> {
46 if state.type_at(arg) == LuaType::Table {
47 return Ok(());
48 }
49 // `n` tracks how many items have been pushed (MT + checked field values).
50 let mut n: i32 = 1;
51 let has_mt = state.get_metatable(arg)?;
52 let mut ok = has_mt;
53
54 // Short-circuit: each field is only checked if all previous checks passed.
55 if ok && (what & TAB_R) != 0 {
56 n += 1;
57 ok = check_field(state, b"__index", n)?;
58 }
59 if ok && (what & TAB_W) != 0 {
60 n += 1;
61 ok = check_field(state, b"__newindex", n)?;
62 }
63 if ok && (what & TAB_L) != 0 {
64 n += 1;
65 ok = check_field(state, b"__len", n)?;
66 }
67
68 if ok {
69 state.pop_n(n as usize);
70 Ok(())
71 } else {
72 state.check_arg_type(arg, LuaType::Table)
73 }
74}
75
76/// Check that argument `n` is a table (or table-like per `w`) and return its
77/// length (the `#` border). This is the shared front-door for every table
78/// function that needs a length. (Ports C's `aux_getn`.)
79fn check_table_and_get_len(state: &mut LuaState, n: i32, w: u32) -> Result<i64, LuaError> {
80 check_tab(state, n, w | TAB_L)?;
81 state.length_at(n)
82}
83
84#[inline]
85fn plain_table_at(state: &mut LuaState, idx: i32) -> Option<GcRef<LuaTable>> {
86 match state.value_at(idx) {
87 LuaValue::Table(tbl) if tbl.metatable().is_none() => Some(tbl),
88 _ => None,
89 }
90}
91
92#[inline]
93fn raw_set_int(
94 state: &mut LuaState,
95 tbl: GcRef<LuaTable>,
96 key: i64,
97 value: LuaValue,
98) -> Result<(), LuaError> {
99 state.gc_table_barrier_back(&tbl, &value);
100 tbl.raw_set_int(state, key, value)
101}
102
103// ─── table.insert ─────────────────────────────────────────────────────────────
104
105/// `table.insert(t, [pos,] v)`. With two args, appends `v` at border+1. With
106/// three, inserts `v` at `pos` (1 <= pos <= border+1) after shifting the tail
107/// up by one; any other arity raises "wrong number of arguments to 'insert'".
108/// The bounds check uses a wrapping unsigned subtract so `pos <= 0` is rejected
109/// alongside `pos > border+1`. Note `border` here is `#t`, which honors a
110/// `__len` metamethod on 5.2+ and uses the primitive length on 5.1.
111pub fn insert(state: &mut LuaState) -> Result<usize, LuaError> {
112 let mut e = check_table_and_get_len(state, 1, TAB_RW)?;
113 e = (e as u64).wrapping_add(1) as i64;
114 let plain_table = plain_table_at(state, 1);
115
116 let pos: i64 = match state.get_top() {
117 2 => {
118 if let Some(tbl) = plain_table {
119 let value = state.value_at(2);
120 raw_set_int(state, tbl, e, value)?;
121 state.pop_n(1);
122 return Ok(0);
123 }
124 e
125 }
126 3 => {
127 let pos = state.check_arg_integer(2)?;
128 // Checks 1 <= pos <= e (wrapping subtraction catches pos <= 0)
129 if !((pos as u64).wrapping_sub(1) < (e as u64)) {
130 return Err(lua_vm::debug::arg_error_impl(
131 state,
132 2,
133 b"position out of bounds",
134 ));
135 }
136 if let Some(tbl) = plain_table {
137 let value = state.value_at(3);
138 let mut i = e;
139 while i > pos {
140 let shifted = tbl.get_int(i - 1);
141 raw_set_int(state, tbl, i, shifted)?;
142 i -= 1;
143 }
144 raw_set_int(state, tbl, pos, value)?;
145 state.pop_n(1);
146 return Ok(0);
147 }
148 // Cache the table once to avoid re-resolving stack slot 1 on every
149 // iteration of the shift loop. C's lua_geti is a single pointer
150 // arithmetic operation; our index_to_value is a function call with
151 // branches, so this saves ~2N index resolutions for shift count N.
152 let tbl = state.value_at(1);
153 let mut i = e;
154 while i > pos {
155 state.table_get_i_value(&tbl, i - 1)?;
156 state.table_set_i_value(&tbl, i)?;
157 i -= 1;
158 }
159 pos
160 }
161 _ => {
162 return Err(LuaError::runtime(format_args!(
163 "wrong number of arguments to 'insert'"
164 )));
165 }
166 };
167 state.table_set_i(1, pos)?;
168 Ok(0)
169}
170
171// ─── table.remove ─────────────────────────────────────────────────────────────
172
173/// `table.remove(t, [pos])`. Removes and returns `t[pos]` (default: the last
174/// element, `#t`), shifting the tail down to close the gap.
175///
176/// The out-of-bounds handling is gated three ways across versions, each pinned
177/// against its reference binary by `v_remove_out_of_bounds_arg_gate_crossversion`:
178///
179/// - **5.1** (legacy `ltablib.c`): there is NO `luaL_argcheck`. An out-of-range
180/// `pos` (outside `[1, size]`) silently removes nothing and returns ZERO
181/// results — never an error.
182/// - **5.2 / 5.3**: `luaL_argcheck((lua_Unsigned)pos - 1u <= size, 1, ...)` —
183/// the offending argument is reported as **#1**.
184/// - **5.4 / 5.5**: the identical check, but the argument index is **#2**.
185pub fn remove(state: &mut LuaState) -> Result<usize, LuaError> {
186 let size = check_table_and_get_len(state, 1, TAB_RW)?;
187 let mut pos = state.opt_arg_integer(2, size)?;
188 if state.global().lua_version == lua_types::LuaVersion::V51 {
189 if !(1 <= pos && pos <= size) {
190 return Ok(0);
191 }
192 } else if pos != size {
193 if !((pos as u64).wrapping_sub(1) <= (size as u64)) {
194 let argn = match state.global().lua_version {
195 lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53 => 1,
196 _ => 2,
197 };
198 return Err(lua_vm::debug::arg_error_impl(
199 state,
200 argn,
201 b"position out of bounds",
202 ));
203 }
204 }
205 // Cache the table once to avoid re-resolving stack slot 1 on every
206 // iteration of the shift loop. C's lua_geti is a single pointer
207 // arithmetic operation; our index_to_value is a function call with
208 // branches, so this saves ~2N index resolutions for shift count N.
209 if let Some(tbl) = plain_table_at(state, 1) {
210 let result = tbl.get_int(pos);
211 state.push(result);
212 while pos < size {
213 let shifted = tbl.get_int(pos + 1);
214 raw_set_int(state, tbl, pos, shifted)?;
215 pos += 1;
216 }
217 raw_set_int(state, tbl, pos, LuaValue::Nil)?;
218 return Ok(1);
219 }
220 let tbl = state.value_at(1);
221 state.table_get_i_value(&tbl, pos)?; // push element to be returned
222 while pos < size {
223 state.table_get_i_value(&tbl, pos + 1)?;
224 state.table_set_i_value(&tbl, pos)?;
225 pos += 1;
226 }
227 state.push(LuaValue::Nil);
228 state.table_set_i_value(&tbl, pos)?; // remove last slot (table[pos] = nil)
229 Ok(1)
230}
231
232// ─── table.move ───────────────────────────────────────────────────────────────
233
234/// `table.move(a1, f, e, t, [a2])`. Copies `a1[f..e]` into `a2[t..]` (or
235/// `a1[t..]` if `a2` is absent), reading source slots through `__index` and
236/// writing destinations through `__newindex` one element at a time. To survive
237/// an overlapping in-place range, it copies FORWARD (increasing index) when the
238/// destination is clear of the source's tail (`t > e || t <= f`, or a distinct
239/// destination table) and BACKWARD (decreasing) otherwise — the order pinned by
240/// `v53_plus_move_*`. Returns the destination table. A 5.3 addition.
241pub fn tmove(state: &mut LuaState) -> Result<usize, LuaError> {
242 let f = state.check_arg_integer(2)?;
243 let e = state.check_arg_integer(3)?;
244 let t = state.check_arg_integer(4)?;
245 let tt: i32 = if !matches!(state.type_at(5), LuaType::None | LuaType::Nil) {
246 5
247 } else {
248 1
249 };
250 check_tab(state, 1, TAB_R)?;
251 check_tab(state, tt, TAB_W)?;
252
253 if e >= f {
254 if !(f > 0 || e < i64::MAX + f) {
255 return Err(lua_vm::debug::arg_error_impl(
256 state,
257 3,
258 b"too many elements to move",
259 ));
260 }
261 let n = e - f + 1;
262 if !(t <= i64::MAX - n + 1) {
263 return Err(lua_vm::debug::arg_error_impl(
264 state,
265 4,
266 b"destination wrap around",
267 ));
268 }
269 // Copy forward (increasing) when safe to do so; backward when ranges overlap.
270 let copy_forward = t > e || t <= f || (tt != 1 && !state.compare(1, tt, CompareOp::Eq)?);
271 if copy_forward {
272 for i in 0..n {
273 state.table_get_i(1, f + i)?;
274 state.table_set_i(tt, t + i)?;
275 }
276 } else {
277 for i in (0..n).rev() {
278 state.table_get_i(1, f + i)?;
279 state.table_set_i(tt, t + i)?;
280 }
281 }
282 }
283 state.push_value_at(tt)?;
284 Ok(1)
285}
286
287// ─── table.concat ─────────────────────────────────────────────────────────────
288
289/// Fetches `t[idx]`; if it is a string-or-number, appends its string form to
290/// `buf` and pops it. A non-coercible element raises the exact "invalid value
291/// (<type>) at index <idx> in table for 'concat'" message (pinned by
292/// `v_table_concat_invalid_value_type_name`). The accumulator is a borrowed
293/// `Vec<u8>` rather than C's stack-backed `luaL_Buffer`.
294fn add_field(state: &mut LuaState, buf: &mut Vec<u8>, idx: i64) -> Result<(), LuaError> {
295 state.table_get_i(1, idx)?;
296 if !matches!(state.type_at(-1), LuaType::String | LuaType::Number) {
297 let type_name = state.type_name_str_at(-1);
298 let msg = format!(
299 "invalid value ({}) at index {} in table for 'concat'",
300 String::from_utf8_lossy(type_name),
301 idx
302 );
303 return crate::auxlib::lua_error(state, msg.as_bytes()).map(|_| ());
304 }
305 let bytes = state
306 .to_bytes_at(-1)
307 .ok_or_else(|| LuaError::runtime(format_args!("invalid value at index {}", idx)))?;
308 buf.extend_from_slice(&bytes);
309 state.pop_n(1);
310 Ok(())
311}
312
313/// `table.concat(t, [sep, [i, [j]]])`. Joins `t[i..j]` (defaults `i=1`,
314/// `j=#t`) with `sep` (default empty) into one string. Each element must be a
315/// string or number; the first that is not raises through [`add_field`].
316pub fn concat(state: &mut LuaState) -> Result<usize, LuaError> {
317 let last = check_table_and_get_len(state, 1, TAB_R)?;
318 // Clone the separator before any stack-mutating calls that might invalidate it.
319 let sep: Vec<u8> = state.opt_arg_lstring(2, Some(b""))?.unwrap_or_default();
320 let mut i = state.opt_arg_integer(3, 1)?;
321 let last = state.opt_arg_integer(4, last)?;
322
323 // A borrowed Vec<u8> accumulates the result, pushed once at the end —
324 // rather than C's luaL_Buffer, which can back-patch the live Lua stack.
325 let mut buf: Vec<u8> = Vec::new();
326 while i < last {
327 add_field(state, &mut buf, i)?;
328 if let Some(err) = state.sandbox_reserve(buf.len() + sep.len()) {
329 return Err(err);
330 }
331 buf.extend_from_slice(&sep);
332 i += 1;
333 }
334 if i == last {
335 add_field(state, &mut buf, i)?;
336 }
337 state.push_lstring(&buf)?;
338 Ok(1)
339}
340
341// ─── table.pack / table.unpack ────────────────────────────────────────────────
342
343/// `table.pack(...)`. Creates a new table with the arguments at integer keys
344/// `1..n` and `t.n` set to the *literal* argument count `n` — holes and
345/// trailing nils included, so `.n` recovers an arity that a `#t` border would
346/// lose (pinned by `v52_plus_pack_n_field_*`). A 5.2 addition.
347pub fn pack(state: &mut LuaState) -> Result<usize, LuaError> {
348 let n = state.get_top();
349 state.create_table(n, 1)?;
350 state.insert(1)?;
351 // table_set_i pops the top; args shift from n+1..=2 down to 1..=n as we pop
352 for i in (1..=n).rev() {
353 state.table_set_i(1, i as i64)?;
354 }
355 state.push(LuaValue::Int(n as i64));
356 state.set_field(1, b"n")?;
357 Ok(1)
358}
359
360/// `table.unpack(t, [i, [j]])`. Pushes `t[i], t[i+1], …, t[j]` (defaults
361/// `i=1`, `j=#t`) and returns the count. An `i > e` range is empty (zero
362/// results); a span of `INT_MAX` or more — including the i64-extreme wrap where
363/// `e - i` overflows to a huge unsigned value — raises "too many results to
364/// unpack" rather than attempting the push (pinned by
365/// `v52_plus_unpack_*` / `v53_plus_unpack_*`). A 5.2 addition.
366pub fn unpack(state: &mut LuaState) -> Result<usize, LuaError> {
367 let i = state.opt_arg_integer(2, 1)?;
368 let e = if matches!(state.type_at(3), LuaType::None | LuaType::Nil) {
369 state.length_at(1)?
370 } else {
371 state.check_arg_integer(3)?
372 };
373 if i > e {
374 return Ok(0); // empty range
375 }
376 let n = (e as u64).wrapping_sub(i as u64);
377 // The size check uses the pre-increment value so that a wrapped-to-0 result
378 // (e.g. i=minI, e=maxI yields n = 2^64-1 pre-inc, 0 post-inc) still trips
379 // the error rather than silently entering a 2^64-iteration loop.
380 if n >= i32::MAX as u64 {
381 return Err(LuaError::runtime(format_args!(
382 "too many results to unpack"
383 )));
384 }
385 let n = n + 1;
386 if !state.check_stack_growth(n as i32) {
387 return Err(LuaError::runtime(format_args!(
388 "too many results to unpack"
389 )));
390 }
391 let n = n as i64;
392 let mut k = i;
393 while k < e {
394 state.table_get_i(1, k)?;
395 k += 1;
396 }
397 state.table_get_i(1, e)?; // push last element
398 Ok(n as usize)
399}
400
401// ─── Quicksort ────────────────────────────────────────────────────────────────
402
403/// A small pseudo-random value used to bias quicksort's pivot selection when
404/// a partition is severely imbalanced.
405///
406/// C uses a small randomised pivot guard to avoid pathological sort
407/// partitions. The Rust port asks the host for entropy when available and
408/// falls back to a deterministic pivot value in sandboxed/bare-WASM hosts.
409fn randomize_pivot(state: &LuaState) -> u32 {
410 let entropy = state.global().entropy_hook.map(|hook| hook()).unwrap_or(0);
411 let mixed = entropy ^ entropy.wrapping_shr(32);
412 (mixed as u32) ^ (mixed as u32).wrapping_shr(16)
413}
414
415/// Sets `table[i]` and `table[j]` respectively (table is at stack position 1).
416fn set2(state: &mut LuaState, i: IdxT, j: IdxT) -> Result<(), LuaError> {
417 // First seti pops the stack top; second seti pops the new top.
418 state.table_set_i(1, i as i64)?;
419 state.table_set_i(1, j as i64)?;
420 Ok(())
421}
422
423/// Compares elements `a` and `b` using the current sort order: either the
424/// `<` operator (if arg 2 is nil) or the user's comparison function at
425/// stack position 2.
426///
427/// The offsets `a-1` and `b-2` compensate for the function and first-argument
428/// copies pushed before the respective values: `a-1` accounts for the function
429/// push; `b-2` accounts for both the function push and the copy of `a`.
430fn sort_comp(state: &mut LuaState, a: i32, b: i32) -> Result<bool, LuaError> {
431 if state.type_at(2) == LuaType::Nil {
432 // No user comparator: use the default `<` operator.
433 return state.compare(a, b, CompareOp::Lt);
434 }
435 // User comparator at stack position 2.
436 state.push_value_at(2)?; // push function
437 state.push_value_at(a - 1)?; // push copy of a (compensate for function push)
438 state.push_value_at(b - 2)?; // push copy of b (compensate for function + a copy)
439 state.call(2, 1)?;
440 let res = state.to_boolean(-1);
441 state.pop_n(1);
442 Ok(res)
443}
444
445/// Partitions `table[lo..=up]` around the pivot value, which the caller has
446/// already pushed onto the top of the Lua stack.
447///
448/// Precondition: `a[lo] <= P == a[up-1] <= a[up]` and `P` is at stack top.
449/// Postcondition: `a[lo..i-1] <= a[i] == P <= a[i+1..up]`; stack is clean.
450/// Returns the final pivot index `i`.
451fn partition(state: &mut LuaState, lo: IdxT, up: IdxT) -> Result<IdxT, LuaError> {
452 let mut i: IdxT = lo;
453 let mut j: IdxT = up - 1;
454 // Entry: stack top is P (pivot value).
455 loop {
456 // Advance i: find first a[i] >= P.
457 // Stack during i-loop body: P(-2), a[i](-1)
458 loop {
459 i += 1;
460 state.table_get_i(1, i as i64)?; // push a[i]
461 if !sort_comp(state, -1, -2)? {
462 // a[i] >= P: leave a[i] on stack and exit
463 break;
464 }
465 // a[i] < P; check for invalid comparator
466 if i == up - 1 {
467 return Err(LuaError::runtime(format_args!(
468 "invalid order function for sorting"
469 )));
470 }
471 state.pop_n(1); // remove a[i]
472 }
473 // Retreat j: find last a[j] <= P.
474 // Stack during j-loop body: P(-3), a[i](-2), a[j](-1)
475 loop {
476 // wrapping_sub mirrors C's unsigned IdxT behavior for edge cases.
477 j = j.wrapping_sub(1);
478 state.table_get_i(1, j as i64)?; // push a[j]
479 if !sort_comp(state, -3, -1)? {
480 // P >= a[j]: leave a[j] on stack and exit
481 break;
482 }
483 // P < a[j]; check for invalid comparator
484 if j < i {
485 return Err(LuaError::runtime(format_args!(
486 "invalid order function for sorting"
487 )));
488 }
489 state.pop_n(1); // remove a[j]
490 }
491 // Stack: P(-3), a[i](-2), a[j](-1)
492 if j < i {
493 // No out-of-place elements; finalize: place pivot at position i.
494 state.pop_n(1); // pop a[j]; stack: P(-2), a[i](-1)
495 set2(state, up - 1, i)?; // table[up-1] = a[i], table[i] = P; stack clean
496 return Ok(i);
497 }
498 // Swap a[i] and a[j] to restore loop invariant.
499 // set2: table[i] = a[j] (pops -1), table[j] = a[i] (pops new -1); stack: P(-1)
500 set2(state, i, j)?;
501 }
502}
503
504/// Chooses a pivot index within `[lo, up]`, randomised by `rnd`.
505fn choose_pivot(lo: IdxT, up: IdxT, rnd: u32) -> IdxT {
506 let r4 = (up - lo) / 4; // range / 4
507 let p = rnd % (r4 * 2) + (lo + r4);
508 debug_assert!(lo + r4 <= p && p <= up - r4);
509 p
510}
511
512/// Sorts `table[lo..=up]` in place, recursing on the smaller partition and
513/// tail-looping on the larger (to bound Rust's call stack). Randomises pivot
514/// selection when a partition is badly imbalanced.
515fn aux_sort(
516 state: &mut LuaState,
517 mut lo: IdxT,
518 mut up: IdxT,
519 mut rnd: u32,
520) -> Result<(), LuaError> {
521 while lo < up {
522 // Step 1: ensure a[lo] <= a[up] (cheap two-element sort)
523 state.table_get_i(1, lo as i64)?; // push a[lo]
524 state.table_get_i(1, up as i64)?; // push a[up]
525 if sort_comp(state, -1, -2)? {
526 set2(state, lo, up)?; // swap so a[lo] <= a[up]
527 } else {
528 state.pop_n(2);
529 }
530 if up - lo == 1 {
531 return Ok(()); // only 2 elements, now sorted
532 }
533
534 // Step 2: choose pivot index
535 let mut p: IdxT = if up - lo < RANLIMIT || rnd == 0 {
536 (lo + up) / 2 // midpoint pivot for small/non-random runs
537 } else {
538 choose_pivot(lo, up, rnd)
539 };
540
541 // Step 3: median-of-three: sort a[lo], a[p], a[up]
542 state.table_get_i(1, p as i64)?; // push a[p]
543 state.table_get_i(1, lo as i64)?; // push a[lo]
544 if sort_comp(state, -2, -1)? {
545 set2(state, p, lo)?; // swap a[p] ↔ a[lo]; stack clean
546 } else {
547 state.pop_n(1); // remove a[lo]; stack: a[p]
548 state.table_get_i(1, up as i64)?; // push a[up]; stack: a[p], a[up]
549 if sort_comp(state, -1, -2)? {
550 set2(state, p, up)?; // swap a[p] ↔ a[up]; stack clean
551 } else {
552 state.pop_n(2); // remove a[up] and a[p]; stack clean
553 }
554 }
555 // Stack is clean at this point.
556 if up - lo == 2 {
557 return Ok(()); // only 3 elements, now sorted
558 }
559
560 // Step 4: move pivot to a[up-1] and call partition.
561 //
562 // Stack evolution:
563 // table_get_i(p): a[p] (-1)
564 // push_value_at(-1): a[p] (-2), a[p]_copy (-1)
565 // table_get_i(up-1): a[p] (-3), a[p]_copy (-2), a[up-1] (-1)
566 // set2(p, up-1): table[p] = a[up-1], table[up-1] = a[p]_copy;
567 // stack: a[p] (-1) ← pivot for partition
568 state.table_get_i(1, p as i64)?;
569 state.push_value_at(-1)?; // duplicate: two copies of pivot on stack
570 state.table_get_i(1, (up - 1) as i64)?;
571 set2(state, p, up - 1)?;
572 // One copy of the pivot value remains at the stack top for partition.
573
574 p = partition(state, lo, up)?;
575 // Stack is clean after partition returns.
576
577 // Step 5: recurse on smaller partition; tail-loop on larger.
578 let n: IdxT;
579 if p - lo < up - p {
580 aux_sort(state, lo, p - 1, rnd)?;
581 n = p - lo;
582 lo = p + 1; // tail: sort [p+1 .. up]
583 } else {
584 aux_sort(state, p + 1, up, rnd)?;
585 n = up - p;
586 up = p - 1; // tail: sort [lo .. p-1]
587 }
588
589 // Re-randomise if the partition was severely imbalanced.
590 if (up - lo) / 128 > n {
591 rnd = randomize_pivot(state);
592 }
593 }
594 Ok(())
595}
596
597/// `table.sort(t, [comp])`: sorts `t` in place using `comp`, or the default
598/// `<` operator if `comp` is absent.
599pub fn sort(state: &mut LuaState) -> Result<usize, LuaError> {
600 let n = check_table_and_get_len(state, 1, TAB_RW)?;
601 if n > 1 {
602 if !(n < i32::MAX as i64) {
603 return Err(lua_vm::debug::arg_error_impl(state, 1, b"array too big"));
604 }
605 if !matches!(state.type_at(2), LuaType::None | LuaType::Nil) {
606 state.check_arg_type(2, LuaType::Function)?;
607 }
608 // Must go through the public C-API set_top (relative to the call
609 // frame); the inherent LuaState::set_top treats its argument as
610 // an absolute stack slot and would corrupt the frame.
611 lua_vm::api::set_top(state, 2)?;
612 aux_sort(state, 1, n as IdxT, 0)?;
613 }
614 Ok(0)
615}
616
617// ─── Registration ─────────────────────────────────────────────────────────────
618
619/// The core `table` roster shared by 5.2-5.5. `move` is filtered out for 5.2
620/// (a 5.3 addition) and `move`/`pack`/`unpack` for 5.1 by [`open_table`], which
621/// also layers the version-specific extras (5.1 legacy, 5.5 `create`) on top.
622pub const TABLE_FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
623 (b"concat", concat),
624 (b"insert", insert),
625 (b"pack", pack),
626 (b"unpack", unpack),
627 (b"remove", remove),
628 (b"move", tmove),
629 (b"sort", sort),
630];
631
632/// `table.create(nseq [, nrec])` — Lua 5.5 addition
633/// (`specs/research/5.5-upstream-delta.md` §5, `ltablib.c`).
634///
635/// Preallocates a table with `nseq` array (sequence) slots and `nrec` hash
636/// (record) slots, returning the empty table. Preallocation is purely a
637/// capacity hint; the returned table is observably empty (length 0, no keys),
638/// so this implementation is behaviorally faithful even though our
639/// `create_table` may treat the sizes as advisory.
640///
641/// Registered into the `table` roster only under [`lua_types::LuaVersion::V55`]
642/// (see [`open_table`]); absent under 5.1-5.4, matching upstream.
643pub fn create(state: &mut LuaState) -> Result<usize, LuaError> {
644 let nseq = state.check_arg_integer(1)?;
645 let nrec = state.opt_arg_integer(2, 0)?;
646 if nseq < 0 || nseq > i32::MAX as i64 {
647 return Err(LuaError::runtime(format_args!(
648 "bad argument #1 to 'create' (size out of range)"
649 )));
650 }
651 if nrec < 0 || nrec > i32::MAX as i64 {
652 return Err(LuaError::runtime(format_args!(
653 "bad argument #2 to 'create' (size out of range)"
654 )));
655 }
656 state.create_table(nseq as i32, nrec as i32)?;
657 Ok(1)
658}
659
660// ─── Lua 5.1 legacy compat functions (`getn`/`setn`/`maxn`/`foreach`/`foreachi`) ──
661//
662// These predate the `#` operator and the 5.2 roster cleanup; they ship only in
663// the default lua5.1.5 build (`ltablib.c`) and are registered under the V51
664// backend by `open_table`. Verified against lua5.1.5; see
665// specs/followup/5.1-roster-syntax.md §1.
666
667/// `table.getn(t)` — the "size" of a sequence, i.e. the border `#t` reports.
668///
669/// In 5.1 `aux_getn` is `luaL_checktype(TABLE)` followed by `luaL_getn`, which
670/// resolves to the primitive length. Mirrors `getn` in 5.1 `ltablib.c`.
671fn getn(state: &mut LuaState) -> Result<usize, LuaError> {
672 state.check_arg_type(1, LuaType::Table)?;
673 let n = state.length_at(1)?;
674 state.push(LuaValue::Int(n));
675 Ok(1)
676}
677
678/// `table.setn(t, n)` — obsolete gravestone. In 5.1 the default build defines
679/// `luaL_setn` as a no-op, so `setn` raises `'setn' is obsolete`. Verified
680/// against lua5.1.5 (`pcall`-able to that exact message).
681fn setn(state: &mut LuaState) -> Result<usize, LuaError> {
682 state.check_arg_type(1, LuaType::Table)?;
683 Err(LuaError::runtime(format_args!("'setn' is obsolete")))
684}
685
686/// `table.maxn(t)` — the largest positive numeric key (0 if none). Iterates the
687/// raw table via `next`, tracking the max numeric key. Mirrors `maxn` in the 5.1
688/// and 5.2 `ltablib.c`; removed in 5.3. Registered for both V51 and V52 by
689/// [`open_table`].
690fn maxn(state: &mut LuaState) -> Result<usize, LuaError> {
691 state.check_arg_type(1, LuaType::Table)?;
692 let mut max: f64 = 0.0;
693 state.push(LuaValue::Nil);
694 while state.table_next(1)? {
695 // Stack: ..., key, value. Drop the value, inspect the key.
696 state.pop_n(1);
697 if matches!(state.type_at(-1), LuaType::Number) {
698 if let Some(v) = state.to_number(-1) {
699 if v > max {
700 max = v;
701 }
702 }
703 }
704 }
705 state.push(LuaValue::Float(max));
706 Ok(1)
707}
708
709/// `table.foreachi(t, f)` — call `f(i, t[i])` for `i` in `1..#t`, stopping early
710/// if `f` returns a non-nil value (which is then returned). Mirrors `foreachi`
711/// in 5.1 `ltablib.c`.
712fn foreachi(state: &mut LuaState) -> Result<usize, LuaError> {
713 state.check_arg_type(1, LuaType::Table)?;
714 state.check_arg_type(2, LuaType::Function)?;
715 let n = state.length_at(1)?;
716 let mut i: i64 = 1;
717 while i <= n {
718 state.push_value_at(2)?;
719 state.push(LuaValue::Int(i));
720 state.table_get_i(1, i)?;
721 state.call(2, 1)?;
722 if !matches!(state.type_at(-1), LuaType::Nil) {
723 return Ok(1);
724 }
725 state.pop_n(1);
726 i += 1;
727 }
728 Ok(0)
729}
730
731/// `table.foreach(t, f)` — call `f(k, v)` for every pair, stopping early if `f`
732/// returns a non-nil value (which is then returned). Mirrors `foreach` in 5.1
733/// `ltablib.c`.
734fn foreach(state: &mut LuaState) -> Result<usize, LuaError> {
735 state.check_arg_type(1, LuaType::Table)?;
736 state.check_arg_type(2, LuaType::Function)?;
737 state.push(LuaValue::Nil);
738 while state.table_next(1)? {
739 // Stack: ..., key, value.
740 state.push_value_at(2)?; // function
741 state.push_value_at(-3)?; // key copy
742 state.push_value_at(-3)?; // value copy
743 state.call(2, 1)?;
744 if !matches!(state.type_at(-1), LuaType::Nil) {
745 return Ok(1);
746 }
747 state.pop_n(2); // remove value and result, leaving key for next()
748 }
749 Ok(0)
750}
751
752// ─── Module opener ────────────────────────────────────────────────────────────
753
754/// Builds the `table` library table for the running version. The base roster is
755/// [`TABLE_FUNCS`], from which 5.1 and 5.2 drop the functions they lack and onto
756/// which 5.1's legacy roster and 5.5's `create` are layered. The per-version
757/// deltas below are each verified against that version's reference binary.
758pub fn open_table(state: &mut LuaState) -> Result<usize, LuaError> {
759 // Per-version roster deltas:
760 // - `table.move` is a Lua 5.3 addition, absent in 5.1/5.2 (verified against
761 // lua5.2.4: `type(table.move)` == "nil").
762 // - `table.pack`/`table.unpack` are Lua 5.2 additions; in 5.1 `unpack` is a
763 // *global* and there is no `table.pack` (verified against lua5.1.5: both
764 // `table.unpack` and `table.pack` are nil). 5.1 instead carries the legacy
765 // `getn`/`setn`/`maxn`/`foreach`/`foreachi` roster.
766 if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
767 let legacy: Vec<(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)> = TABLE_FUNCS
768 .iter()
769 .filter(|(name, _)| {
770 *name != b"move".as_slice()
771 && *name != b"pack".as_slice()
772 && *name != b"unpack".as_slice()
773 })
774 .copied()
775 .collect();
776 state.new_lib(&legacy)?;
777 const LEGACY_FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
778 (b"getn", getn),
779 (b"setn", setn),
780 (b"maxn", maxn),
781 (b"foreach", foreach),
782 (b"foreachi", foreachi),
783 ];
784 state.set_funcs_with_upvalues(LEGACY_FUNCS, 0)?;
785 } else if matches!(state.global().lua_version, lua_types::LuaVersion::V52) {
786 let without_move: Vec<(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)> = TABLE_FUNCS
787 .iter()
788 .filter(|(name, _)| *name != b"move".as_slice())
789 .copied()
790 .collect();
791 state.new_lib(&without_move)?;
792 // `table.maxn` survives into 5.2 (it is removed in 5.3). The legacy
793 // `getn`/`setn`/`foreach`/`foreachi` roster, by contrast, is 5.1-only.
794 // Verified against lua5.2.4: `type(table.maxn)` == "function" but
795 // `type(table.getn)` == "nil".
796 const V52_LEGACY: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] =
797 &[(b"maxn", maxn)];
798 state.set_funcs_with_upvalues(V52_LEGACY, 0)?;
799 } else {
800 state.new_lib(TABLE_FUNCS)?;
801 }
802 // Per-version roster delta: `table.create` is a Lua 5.5 addition
803 // (`specs/research/5.5-upstream-delta.md` §5), absent in 5.1-5.4. Register
804 // it only on the V55 backend so the version seam carries a real,
805 // script-observable stdlib difference. `new_lib` leaves the new table on
806 // the stack top, so we register `create` into it directly.
807 if matches!(state.global().lua_version, lua_types::LuaVersion::V55) {
808 const CREATE_FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] =
809 &[(b"create", create)];
810 state.set_funcs_with_upvalues(CREATE_FUNCS, 0)?;
811 }
812 Ok(1)
813}