[Space Lua] Implement string.pack, string.unpack and string.packsize (#1851)

The three binary-packing functions from Lua are now implemented in
a dedicated `string_pack.ts` module and wired into `stringApi`.

Format parsing follows the exact option set of Lua:

* signed and unsigned integers of configurable width
  (`b`/`B`/`h`/`H`/`l`/`L`/`j`/`J`/`T`/`i`/`I`),
* IEEE 754 single and double precision floats (`f`/`d`/`n`),
* fixed-length strings (`c`),
* length-prefixed strings (`s`),
* zero-terminated strings (`z`),
* padding bytes (`x`),
* alignment padding (`X`), and
* endianness/alignment modifiers (`<`/`>`/`=`/`!`).

`string.packsize` rejects variable-length formats (`s` and `z`) as Lua
requires.

`string.unpack` returns all unpacked values followed by the
next position integer, matching the Lua contract exactly.

Test suite extended in separates `string_pack_test.lua` file. Passes
both Lua and Space Lua execution.

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
This commit is contained in:
Matouš Jan Fialka
2026-02-25 09:29:14 +01:00
committed by GitHub
parent cebc834469
commit fd4ff8518d
4 changed files with 682 additions and 0 deletions
+6
View File
@@ -16,6 +16,7 @@ import {
patternGsub,
patternMatch,
} from "./pattern.ts";
import { strPackFn, strPackSizeFn, strUnpackFn } from "./string_pack.ts";
function capturesToLua(caps: CaptureResult[]): any {
if (caps.length === 0) {return null;}
@@ -162,10 +163,15 @@ export const stringApi = new LuaTable({
}
return "";
}),
split: new LuaBuiltinFunction((_sf, s: string, sep: string) => {
return s.split(sep);
}),
pack: strPackFn,
unpack: strUnpackFn,
packsize: strPackSizeFn,
// Non-standard extensions
startsWith: new LuaBuiltinFunction((_sf, s: string, prefix: string) => {
return s.startsWith(prefix);