@@ -558,28 +558,41 @@ export abstract class LuaTranspiler {
558558 const variable = ( node . initializer as ts . VariableDeclarationList ) . declarations [ 0 ] ;
559559
560560 // Transpile expression
561- const expression = this . transpileExpression ( node . expression ) ;
561+ const iterable = this . transpileExpression ( node . expression ) ;
562562
563563 // Use ipairs for array types, pairs otherwise
564564 const isArray = tsHelper . isArrayType ( this . checker . getTypeAtLocation ( node . expression ) , this . checker ) ;
565- const pairs = isArray ? "ipairs" : "pairs" ;
566565
567- // Make header
568566 let result = "" ;
569- if ( ts . isIdentifier ( variable . name ) ) {
570- result = this . indent + `for _, ${ this . transpileIdentifier ( variable . name ) } in ${ pairs } (${ expression } ) do\n` ;
571- } else if ( ts . isArrayBindingPattern ( variable . name ) ) {
572- const valueVar = "__forOfValue" + this . genVarCounter ;
573- result = this . indent + `for _, ${ valueVar } in ${ pairs } (${ expression } ) do\n` ;
574- const declaration = ts . createVariableDeclaration ( variable . name , undefined , ts . createIdentifier ( valueVar ) ) ;
575- result += this . indent + this . transpileVariableDeclaration ( declaration ) ;
567+
568+ if ( ! isArray && ts . isIdentifier ( variable . name ) ) {
569+ result = this . indent + `for _, ${ this . transpileIdentifier ( variable . name ) } in pairs(${ iterable } ) do\n` ;
570+ } else {
571+ let itemVariable : ts . Identifier ;
572+ if ( isArray ) {
573+ // Cache the expression result
574+ result += this . indent + `local __loopVariable${ this . genVarCounter } = ${ iterable } ;\n` ;
575+ result += this . indent + `for i${ this . genVarCounter } =1, #__loopVariable${ this . genVarCounter } do\n` ;
576+ itemVariable = ts . createIdentifier ( `__loopVariable${ this . genVarCounter } [i${ this . genVarCounter } ]` ) ;
577+ } else {
578+ const variableName = `__forOfValue${ this . genVarCounter } ` ;
579+ itemVariable = ts . createIdentifier ( variableName ) ;
580+ result += this . indent + `for _, ${ variableName } in pairs(${ iterable } ) do\n` ;
581+ }
582+
583+ const declaration = ts . createVariableDeclaration ( variable . name , undefined , itemVariable ) ;
584+ this . pushIndent ( ) ;
585+ result += this . indent + this . transpileVariableDeclaration ( declaration ) + ";\n" ;
586+ this . popIndent ( ) ;
576587 }
577588
578589 // For body
579590 this . pushIndent ( ) ;
580591 result += this . transpileLoopBody ( node ) ;
581592 this . popIndent ( ) ;
582593
594+ this . genVarCounter ++ ;
595+
583596 return result + this . indent + "end\n" ;
584597 }
585598
0 commit comments