From ccea2200ac7565a6441a9489df6383296cc768b5 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Thu, 16 Jan 2025 12:35:15 +0100 Subject: [PATCH] JS iterable handling --- common/space_lua/eval.ts | 2 ++ common/space_lua/stdlib/js.ts | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/common/space_lua/eval.ts b/common/space_lua/eval.ts index 6790aa18..6f5bc125 100644 --- a/common/space_lua/eval.ts +++ b/common/space_lua/eval.ts @@ -730,9 +730,11 @@ export async function evalStatement( ), ).flatten(); let iteratorValue: ILuaFunction | any = iteratorMultiRes.values[0]; + // Handle the case where the iterator is a table and we need to call the each function if (Array.isArray(iteratorValue) || iteratorValue instanceof LuaTable) { iteratorValue = env.get("each").call(sf, iteratorValue); } + if (!iteratorValue?.call) { console.error("Cannot iterate over", iteratorMultiRes.values[0]); throw new LuaRuntimeError( diff --git a/common/space_lua/stdlib/js.ts b/common/space_lua/stdlib/js.ts index 23ee8838..c25b67e1 100644 --- a/common/space_lua/stdlib/js.ts +++ b/common/space_lua/stdlib/js.ts @@ -14,7 +14,6 @@ export const jsApi = new LuaTable({ */ new: new LuaBuiltinFunction( (_sf, constructorFn: any, ...args) => { - console.log("New", constructorFn, args); return new constructorFn( ...args.map(luaValueToJS), ); @@ -33,6 +32,16 @@ export const jsApi = new LuaTable({ } return m; }), + each_iterable: new LuaBuiltinFunction((_sf, val) => { + let iterator = val[Symbol.asyncIterator](); + return async () => { + const result = await iterator.next(); + if (result.done) { + return; + } + return result.value; + }; + }), /** * Converts a JavaScript value to a Lua value. * @param val - The JavaScript value to convert.