Skip to content

Commit 720a4dc

Browse files
tomblindPerryvw
authored andcommitted
Array support in __TS__Iterator (#556)
1 parent 1d2cd13 commit 720a4dc

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

src/lualib/Iterator.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
function __TS__Iterator<T>(this: void, iterable: Iterable<T>): (this: void) => T {
2-
const iterator = iterable[Symbol.iterator]();
3-
return () => {
4-
const result = iterator.next();
5-
if (!result.done) {
6-
return result.value;
7-
} else {
8-
return undefined;
9-
}
10-
};
2+
if (iterable[Symbol.iterator]) {
3+
const iterator = iterable[Symbol.iterator]();
4+
return () => {
5+
const result = iterator.next();
6+
if (!result.done) {
7+
return result.value;
8+
} else {
9+
return undefined;
10+
}
11+
};
12+
} else {
13+
let i = 0;
14+
return () => {
15+
i = i + 1;
16+
return iterable[i];
17+
};
18+
}
1119
}

test/unit/loops.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,20 @@ test("forof destructuring with iterator and existing variables", () => {
504504
expect(result).toBe("0a1b2c");
505505
});
506506

507+
test("forof with array typed as iterable", () => {
508+
const code = `
509+
function foo(): Iterable<string> {
510+
return ["A", "B", "C"];
511+
}
512+
let result = "";
513+
for (const x of foo()) {
514+
result += x;
515+
}
516+
return result;
517+
`;
518+
expect(util.transpileAndExecute(code)).toBe("ABC");
519+
});
520+
507521
test("forof lua iterator", () => {
508522
const code = `
509523
const arr = ["a", "b", "c"];

0 commit comments

Comments
 (0)