Skip to content

Commit 8ebfc31

Browse files
committed
Fix for repeat...until scoping
fixes #657 Also added a small optimization to prevent double-negation in until-condition
1 parent 6058224 commit 8ebfc31

File tree

3 files changed

+49
-8
lines changed

3 files changed

+49
-8
lines changed

src/LuaTransformer.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2216,14 +2216,17 @@ export class LuaTransformer {
22162216
}
22172217

22182218
public transformDoStatement(statement: ts.DoStatement): StatementVisitResult {
2219-
return tstl.createRepeatStatement(
2220-
tstl.createBlock(this.transformLoopBody(statement)),
2221-
tstl.createUnaryExpression(
2222-
tstl.createParenthesizedExpression(this.transformExpression(statement.expression)),
2219+
const body = tstl.createDoStatement(this.transformLoopBody(statement));
2220+
let condition = this.transformExpression(statement.expression);
2221+
if (tstl.isUnaryExpression(condition) && condition.operator === tstl.SyntaxKind.NotOperator) {
2222+
condition = condition.operand;
2223+
} else {
2224+
condition = tstl.createUnaryExpression(
2225+
tstl.createParenthesizedExpression(condition),
22232226
tstl.SyntaxKind.NotOperator
2224-
),
2225-
statement
2226-
);
2227+
);
2228+
}
2229+
return tstl.createRepeatStatement(tstl.createBlock([body]), condition, statement);
22272230
}
22282231

22292232
public transformForStatement(statement: ts.ForStatement): StatementVisitResult {

test/translation/__snapshots__/transformation.spec.ts.snap

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,9 @@ end"
150150
exports[`Transformation (do) 1`] = `
151151
"local e = 10
152152
repeat
153-
e = e - 1
153+
do
154+
e = e - 1
155+
end
154156
until not (e > 0)"
155157
`;
156158

test/unit/loops.spec.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,3 +981,39 @@ test.each([
981981
).message
982982
);
983983
});
984+
985+
test("do...while", () => {
986+
const code = `
987+
let result = 0;
988+
do {
989+
++result;
990+
} while (result < 2);
991+
return result;
992+
`;
993+
expect(util.transpileAndExecute(code)).toBe(2);
994+
});
995+
996+
test("do...while scoping", () => {
997+
const code = `
998+
let x = 0;
999+
let result = 0;
1000+
do {
1001+
let x = 1;
1002+
++result;
1003+
} while (x === 0 && result < 2);
1004+
return result;
1005+
`;
1006+
expect(util.transpileAndExecute(code)).toBe(2);
1007+
});
1008+
1009+
test("do...while double-negation", () => {
1010+
const code = `
1011+
let result = 0;
1012+
do {
1013+
++result;
1014+
} while (!(result >= 2));
1015+
return result;
1016+
`;
1017+
expect(util.transpileString(code)).not.toMatch("not");
1018+
expect(util.transpileAndExecute(code)).toBe(2);
1019+
});

0 commit comments

Comments
 (0)