Skip to content

Commit fddc544

Browse files
authored
Make strings iterable (#891)
* Make strings iterable * Add changelog
1 parent 03fae35 commit fddc544

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/lualib/Iterator.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,25 @@ function __TS__IteratorIteratorStep<T>(this: Iterator<T>): [true, T] | [] {
1616
return [true, result.value];
1717
}
1818

19+
/** @tupleReturn */
20+
function __TS__IteratorStringStep(this: string, index: number): [number, string] | [] {
21+
index += 1;
22+
if (index > this.length) return [];
23+
return [index, string.sub(this, index, index)];
24+
}
25+
1926
/** @tupleReturn */
2027
function __TS__Iterator<T>(
2128
this: void,
2229
iterable: Iterable<T> | GeneratorIterator | readonly T[]
23-
): [(...args: any[]) => [any, T] | [], ...any[]] {
30+
): [(...args: any[]) => [any, any] | [], ...any[]] {
2431
if ("____coroutine" in iterable) {
2532
return [__TS__IteratorGeneratorStep, iterable];
2633
} else if (iterable[Symbol.iterator]) {
2734
const iterator = iterable[Symbol.iterator]();
2835
return [__TS__IteratorIteratorStep, iterator];
36+
} else if (typeof iterable === "string") {
37+
return [__TS__IteratorStringStep, iterable, 0];
2938
} else {
3039
return ipairs(iterable as readonly T[]) as any;
3140
}

test/unit/loops.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,16 @@ test("forof with array typed as iterable", () => {
442442
`.expectToMatchJsResult();
443443
});
444444

445+
test.each(["", "abc", "a\0c"])("forof string (%p)", string => {
446+
util.testFunctionTemplate`
447+
const results: string[] = [];
448+
for (const x of ${string}) {
449+
results.push(x);
450+
}
451+
return results;
452+
`.expectToMatchJsResult();
453+
});
454+
445455
describe("for...of empty destructuring", () => {
446456
const declareTests = (destructuringPrefix: string) => {
447457
test("array", () => {

0 commit comments

Comments
 (0)