From e20c1f518089a9b9024f554a6eb99cb7f95c5f8c Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 1 Jun 2020 01:40:59 +0000 Subject: [PATCH 1/2] Make strings iterable --- src/lualib/Iterator.ts | 11 ++++++++++- test/unit/loops.spec.ts | 10 ++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/lualib/Iterator.ts b/src/lualib/Iterator.ts index 897d4a7a2..e55de6404 100644 --- a/src/lualib/Iterator.ts +++ b/src/lualib/Iterator.ts @@ -16,16 +16,25 @@ function __TS__IteratorIteratorStep(this: Iterator): [true, T] | [] { return [true, result.value]; } +/** @tupleReturn */ +function __TS__IteratorStringStep(this: string, index: number): [number, string] | [] { + index += 1; + if (index > this.length) return []; + return [index, string.sub(this, index, index)]; +} + /** @tupleReturn */ function __TS__Iterator( this: void, iterable: Iterable | GeneratorIterator | readonly T[] -): [(...args: any[]) => [any, T] | [], ...any[]] { +): [(...args: any[]) => [any, any] | [], ...any[]] { if ("____coroutine" in iterable) { return [__TS__IteratorGeneratorStep, iterable]; } else if (iterable[Symbol.iterator]) { const iterator = iterable[Symbol.iterator](); return [__TS__IteratorIteratorStep, iterator]; + } else if (typeof iterable === "string") { + return [__TS__IteratorStringStep, iterable, 0]; } else { return ipairs(iterable as readonly T[]) as any; } diff --git a/test/unit/loops.spec.ts b/test/unit/loops.spec.ts index 0959d31b8..b35bbd767 100644 --- a/test/unit/loops.spec.ts +++ b/test/unit/loops.spec.ts @@ -442,6 +442,16 @@ test("forof with array typed as iterable", () => { `.expectToMatchJsResult(); }); +test.each(["", "abc", "a\0c"])("forof string (%p)", string => { + util.testFunctionTemplate` + const results: string[] = []; + for (const x of ${string}) { + results.push(x); + } + return results; + `.expectToMatchJsResult(); +}); + describe("for...of empty destructuring", () => { const declareTests = (destructuringPrefix: string) => { test("array", () => { From 6f73d3999da2698e29a88e79bc22551b009e7c7d Mon Sep 17 00:00:00 2001 From: ark120202 Date: Mon, 1 Jun 2020 01:56:04 +0000 Subject: [PATCH 2/2] Add changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a5842b0a..c81933900 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- Strings now can be iterated over + ## 0.34.0 - Added new `"luaTarget"` option value - `"universal"`. Choosing this target makes TypeScriptToLua generate code compatible with all supported Lua targets.