@@ -49,14 +49,25 @@ export const transformSwitchStatement: FunctionVisitor<ts.SwitchStatement> = (st
4949 ) ;
5050 }
5151
52- // Starting from the back, concatenating ifs into one big if/elseif statement
52+ let statements : lua . Statement [ ] = [ ] ;
53+
54+ // Default will either be the only statement, or the else in the if chain
5355 const defaultIndex = statement . caseBlock . clauses . findIndex ( c => ts . isDefaultClause ( c ) ) ;
54- const concatenatedIf = statement . caseBlock . clauses . reduceRight < lua . IfStatement | lua . Block | undefined > (
55- ( previousCondition , clause , index ) => {
56- if ( ts . isDefaultClause ( clause ) ) {
57- // Skip default clause here (needs to be included to ensure index lines up with index later)
58- return previousCondition ;
59- }
56+ const defaultBody = defaultIndex >= 0 ? caseBody [ defaultIndex ] : undefined ;
57+ if ( defaultBody && statement . caseBlock . clauses . length === 1 ) {
58+ statements . push ( lua . createDoStatement ( defaultBody ) ) ;
59+ } else {
60+ let concatenatedIf : lua . IfStatement | undefined = undefined ;
61+ let previousCondition : lua . IfStatement | lua . Block | undefined = defaultBody
62+ ? lua . createBlock ( defaultBody )
63+ : undefined ;
64+
65+ // Starting from the back, concatenating ifs into one big if/elseif/[else] statement
66+ for ( let i = statement . caseBlock . clauses . length - 1 ; i >= 0 ; i -- ) {
67+ const clause = statement . caseBlock . clauses [ i ] ;
68+
69+ // Skip default clause to keep index aligned, handle in else block
70+ if ( ts . isDefaultClause ( clause ) ) continue ;
6071
6172 // If the clause condition holds, go to the correct label
6273 const condition = lua . createBinaryExpression (
@@ -65,15 +76,10 @@ export const transformSwitchStatement: FunctionVisitor<ts.SwitchStatement> = (st
6576 lua . SyntaxKind . EqualityOperator
6677 ) ;
6778
68- return lua . createIfStatement ( condition , lua . createBlock ( caseBody [ index ] ) , previousCondition ) ;
69- } ,
70- defaultIndex >= 0 ? lua . createBlock ( caseBody [ defaultIndex ] ) : undefined
71- ) ;
72-
73- let statements : lua . Statement [ ] = [ ] ;
74-
75- if ( concatenatedIf ) {
76- statements . push ( concatenatedIf as unknown as lua . IfStatement ) ;
79+ concatenatedIf = lua . createIfStatement ( condition , lua . createBlock ( caseBody [ i ] ) , previousCondition ) ;
80+ previousCondition = concatenatedIf ;
81+ }
82+ if ( concatenatedIf ) statements . push ( concatenatedIf ) ;
7783 }
7884
7985 statements = performHoisting ( context , statements ) ;
0 commit comments