Skip to content

Commit 45fb7eb

Browse files
authored
Fix loop variables incorrectly being made global (#1641)
1 parent 9a9817e commit 45fb7eb

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/transformation/visitors/loops/for.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@ import { FunctionVisitor } from "../../context";
44
import { transformInPrecedingStatementScope } from "../../utils/preceding-statements";
55
import { checkVariableDeclarationList, transformVariableDeclaration } from "../variable-declaration";
66
import { invertCondition, transformLoopBody } from "./utils";
7+
import { ScopeType } from "../../utils/scope";
78

89
export const transformForStatement: FunctionVisitor<ts.ForStatement> = (statement, context) => {
910
const result: lua.Statement[] = [];
1011

12+
context.pushScope(ScopeType.Loop);
13+
1114
if (statement.initializer) {
1215
if (ts.isVariableDeclarationList(statement.initializer)) {
1316
checkVariableDeclarationList(context, statement.initializer);
@@ -61,5 +64,7 @@ export const transformForStatement: FunctionVisitor<ts.ForStatement> = (statemen
6164
// while (condition) do ... end
6265
result.push(lua.createWhileStatement(lua.createBlock(body), condition, statement));
6366

67+
context.popScope();
68+
6469
return lua.createDoStatement(result, statement);
6570
};

test/unit/loops.spec.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -540,10 +540,10 @@ for (const testCase of [
540540
"for (const a of []) { continue; }",
541541
]) {
542542
const expectContinueVariable: util.TapCallback = builder =>
543-
expect(builder.getMainLuaCodeChunk()).toMatch("local __continue2");
543+
expect(builder.getMainLuaCodeChunk()).toMatch(/local __continue\d+/);
544544

545545
const expectContinueGotoLabel: util.TapCallback = builder =>
546-
expect(builder.getMainLuaCodeChunk()).toMatch("::__continue2::");
546+
expect(builder.getMainLuaCodeChunk()).toMatch(/::__continue\d+::/);
547547

548548
const expectContinueStatement: util.TapCallback = builder =>
549549
expect(builder.getMainLuaCodeChunk()).toMatch("continue;");
@@ -638,3 +638,12 @@ test("for...in with pre-defined variable keeps last value", () => {
638638
// Need custom matcher because order is not guaranteed in neither JS nor Lua
639639
expect([keyX, keyFoo]).toContain(result);
640640
});
641+
642+
// https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1631
643+
test("loop variables should not be global (#1631)", () => {
644+
const code = util.testModule`
645+
for (let val = 0; val < 2; ++val) {}
646+
`.getMainLuaCodeChunk();
647+
648+
expect(code).toContain("local val");
649+
});

0 commit comments

Comments
 (0)