[Space Lua] Implement table.move

Implement `table.move(a1, f, e, t [,a2])`.

The implementation copies elements `a1[f..e]` to `a2[t..t+(e-f)]`
defaulting `a2` to `a1` and returning `a2` as follows:

* empty ranges (`e < f`) are "no-op",

* for in-table copies where `t > f` loop backwards to prevent unread
  source slots from being clobbered before they are read (note: the only
  case where overlap is destructive,

* cross-table copies always run forwards since there is no aliasing.

Add test suite that covers:

* non-overlapping copies,
* cross-table copies,
* both overlap directions,
* same position identity,
* empty ranges, and
* single element moves.

Each of the above is tested with both scalar and nested-table values.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
This commit is contained in:
Matouš Jan Fialka
2026-02-20 08:28:24 +01:00
parent 8cecd0985c
commit af0086fcfb
2 changed files with 179 additions and 0 deletions
+50
View File
@@ -205,6 +205,56 @@ export const tableApi = new LuaTable({
},
),
/**
* Moves elements from table a1 into table a2 (defaults to a1).
* Equivalent to: `for i = f, e do a2[t+(i-f)] = a1[i] end`
* Handles overlapping ranges within the same table correctly.
* @param a1 - Source table.
* @param f - First source index (inclusive).
* @param e - Last source index (inclusive).
* @param t - Destination start index.
* @param a2 - Destination table (defaults to a1).
* @returns a2.
*/
move: new LuaBuiltinFunction(
async (
sf,
a1: LuaTable | any[],
f: number,
e: number,
t: number,
a2?: LuaTable | any[],
) => {
// a2 defaults to a1
if (a2 === undefined || a2 === null) {
a2 = a1;
}
// Empty range: nothing to do, return destination
if (e < f) {
return a2;
}
const count = e - f + 1;
// When source and destination overlap and destination is ahead of
// source then copy backwards to avoid clobbering unread values.
if (t > f && a2 === a1) {
for (let i = count - 1; i >= 0; i--) {
const v = await luaGet(a1, f + i, sf.astCtx ?? null, sf);
await luaSet(a2, t + i, v, sf);
}
} else {
for (let i = 0; i < count; i++) {
const v = await luaGet(a1, f + i, sf.astCtx ?? null, sf);
await luaSet(a2, t + i, v, sf);
}
}
return a2;
},
),
/**
* Sorts a table.
* @param tbl - The table to sort.