silverbullet/common/space_lua/stdlib/table.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-10-10 02:35:07 +08:00
import {
2024-10-11 21:34:27 +08:00
type ILuaFunction,
LuaBuiltinFunction,
2025-01-14 03:25:39 +08:00
luaEquals,
LuaRuntimeError,
2024-10-11 21:34:27 +08:00
LuaTable,
2025-01-14 03:25:39 +08:00
type LuaValue,
2024-10-10 02:35:07 +08:00
} from "$common/space_lua/runtime.ts";
export const tableApi = new LuaTable({
2024-10-11 21:34:27 +08:00
concat: new LuaBuiltinFunction(
2024-10-20 21:06:23 +08:00
(_sf, tbl: LuaTable, sep?: string, i?: number, j?: number) => {
2024-10-11 21:34:27 +08:00
sep = sep ?? "";
i = i ?? 1;
j = j ?? tbl.length;
const result = [];
for (let k = i; k <= j; k++) {
result.push(tbl.get(k));
}
return result.join(sep);
},
),
insert: new LuaBuiltinFunction(
2024-10-20 21:06:23 +08:00
(_sf, tbl: LuaTable, posOrValue: number | any, value?: any) => {
2024-10-11 21:34:27 +08:00
if (value === undefined) {
2025-01-08 18:12:26 +08:00
let pos = 1;
while (tbl.get(pos) !== null) {
pos++;
}
tbl.set(pos, posOrValue);
} else {
tbl.insert(posOrValue, value);
2024-10-11 21:34:27 +08:00
}
},
),
2024-10-20 21:06:23 +08:00
remove: new LuaBuiltinFunction((_sf, tbl: LuaTable, pos?: number) => {
2024-10-11 21:34:27 +08:00
pos = pos ?? tbl.length;
tbl.remove(pos);
}),
2024-10-20 21:06:23 +08:00
sort: new LuaBuiltinFunction((sf, tbl: LuaTable, comp?: ILuaFunction) => {
return tbl.sort(comp, sf);
2024-10-11 21:34:27 +08:00
}),
keys: new LuaBuiltinFunction((_sf, tbl: LuaTable) => {
return tbl.keys();
}),
2025-01-14 03:25:39 +08:00
includes: new LuaBuiltinFunction(
(sf, tbl: LuaTable | Record<string, any>, value: LuaValue) => {
if (tbl instanceof LuaTable) {
// Iterate over the table
for (const key of tbl.keys()) {
if (luaEquals(tbl.get(key), value)) {
return true;
}
}
return false;
} else if (Array.isArray(tbl)) {
return !!tbl.find((item) => luaEquals(item, value));
} else {
throw new LuaRuntimeError(
`Cannot use includes on a non-table or non-array value`,
sf,
);
}
},
),
2024-10-10 02:35:07 +08:00
});