@@ -2628,10 +2628,6 @@ export class LuaTransformer {
26282628 }
26292629
26302630 public transformForInStatement ( statement : ts . ForInStatement ) : StatementVisitResult {
2631- // Get variable identifier
2632- const variable = ( statement . initializer as ts . VariableDeclarationList ) . declarations [ 0 ] ;
2633- const identifier = variable . name as ts . Identifier ;
2634-
26352631 // Transpile expression
26362632 const pairsIdentifier = tstl . createIdentifier ( "pairs" ) ;
26372633 const expression = this . transformExpression ( statement . expression ) ;
@@ -2643,7 +2639,30 @@ export class LuaTransformer {
26432639
26442640 const body = tstl . createBlock ( this . transformLoopBody ( statement ) ) ;
26452641
2646- return tstl . createForInStatement ( body , [ this . transformIdentifier ( identifier ) ] , [ pairsCall ] , statement ) ;
2642+ // Transform iteration variable
2643+ // TODO: After the transformation pipeline refactor we should look at refactoring this together with the
2644+ // for-of initializer transformation.
2645+ let iterationVariable : tstl . Identifier ;
2646+ if (
2647+ ts . isVariableDeclarationList ( statement . initializer ) &&
2648+ ts . isIdentifier ( statement . initializer . declarations [ 0 ] . name )
2649+ ) {
2650+ iterationVariable = this . transformIdentifier ( statement . initializer . declarations [ 0 ] . name ) ;
2651+ } else if ( ts . isIdentifier ( statement . initializer ) ) {
2652+ // Iteration variable becomes ____key
2653+ iterationVariable = tstl . createIdentifier ( "____key" ) ;
2654+ // Push variable = ____key to the start of the loop body to match TS scoping
2655+ const initializer = tstl . createAssignmentStatement (
2656+ this . transformIdentifier ( statement . initializer ) ,
2657+ iterationVariable
2658+ ) ;
2659+ body . statements . unshift ( initializer ) ;
2660+ } else {
2661+ // This should never occur
2662+ throw TSTLErrors . UnsupportedForInVariable ( statement . initializer ) ;
2663+ }
2664+
2665+ return tstl . createForInStatement ( body , [ iterationVariable ] , [ pairsCall ] , statement ) ;
26472666 }
26482667
26492668 public transformSwitchStatement ( statement : ts . SwitchStatement ) : StatementVisitResult {
0 commit comments