@@ -687,24 +687,44 @@ export abstract class LuaTranspiler {
687687 }
688688
689689 public transpileTry ( node : ts . TryStatement ) : string {
690- let tryFunc = "function()\n" ;
690+ let result = this . indent + "do\n" ;
691+ this . pushIndent ( ) ;
692+
693+ result += this . indent ;
694+ if ( node . catchClause ) {
695+ result += "local __TS_try" ;
696+ if ( node . catchClause . variableDeclaration ) {
697+ const variableName = this . transpileIdentifier (
698+ node . catchClause . variableDeclaration . name as ts . Identifier ) ;
699+ result += ", " + variableName ;
700+ }
701+ result += " = " ;
702+ }
703+
704+ result += "pcall(function()\n" ;
691705 this . pushIndent ( ) ;
692- tryFunc += this . transpileBlock ( node . tryBlock ) ;
706+ result += this . transpileBlock ( node . tryBlock ) ;
693707 this . popIndent ( ) ;
694- tryFunc += "end" ;
695- let catchFunc = "function(e)\nend" ;
696- if ( node . catchClause && node . catchClause . variableDeclaration ) {
697- const variableName = this . transpileIdentifier ( node . catchClause . variableDeclaration . name as ts . Identifier ) ;
698- catchFunc = this . indent + `function(${ variableName } )\n` ;
708+ result += this . indent + "end);\n" ;
709+
710+ if ( node . catchClause ) {
711+ result += this . indent + `if not __TS_try then\n` ;
699712 this . pushIndent ( ) ;
700- catchFunc += this . transpileBlock ( node . catchClause . block ) ;
713+ result += this . transpileBlock ( node . catchClause . block ) ;
701714 this . popIndent ( ) ;
702- catchFunc += "end" ;
715+ result += this . indent + "end\n " ;
703716 }
704- let result = this . indent + `xpcall( ${ tryFunc } ,\n ${ catchFunc } )\n` ;
717+
705718 if ( node . finallyBlock ) {
719+ result += this . indent + "do\n" ;
720+ this . pushIndent ( ) ;
706721 result += this . transpileBlock ( node . finallyBlock ) ;
722+ this . popIndent ( ) ;
723+ result += this . indent + "end\n" ;
707724 }
725+
726+ this . popIndent ( ) ;
727+ result += this . indent + "end\n" ;
708728 return result ;
709729 }
710730
0 commit comments