@@ -691,6 +691,30 @@ export abstract class LuaTranspiler {
691691 }
692692 }
693693
694+ public escapeString ( text : string ) : string {
695+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
696+ const escapeSequences : Array < [ RegExp , string ] > = [
697+ [ / [ \\ ] / g, "\\\\" ] ,
698+ [ / [ \' ] / g, "\\\'" ] ,
699+ [ / [ \` ] / g, "\\\`" ] ,
700+ [ / [ \" ] / g, "\\\"" ] ,
701+ [ / [ \n ] / g, "\\n" ] ,
702+ [ / [ \r ] / g, "\\r" ] ,
703+ [ / [ \v ] / g, "\\v" ] ,
704+ [ / [ \t ] / g, "\\t" ] ,
705+ [ / [ \b ] / g, "\\b" ] ,
706+ [ / [ \f ] / g, "\\f" ] ,
707+ [ / [ \0 ] / g, "\\0" ] ,
708+ ] ;
709+
710+ if ( text . length > 0 ) {
711+ for ( const [ regex , replacement ] of escapeSequences ) {
712+ text = text . replace ( regex , replacement ) ;
713+ }
714+ }
715+ return text ;
716+ }
717+
694718 public transpileExpression ( node : ts . Node , brackets ?: boolean ) : string {
695719 switch ( node . kind ) {
696720 case ts . SyntaxKind . BinaryExpression :
@@ -714,7 +738,7 @@ export abstract class LuaTranspiler {
714738 return this . transpileIdentifier ( node as ts . Identifier ) ;
715739 case ts . SyntaxKind . StringLiteral :
716740 case ts . SyntaxKind . NoSubstitutionTemplateLiteral :
717- const text = ( node as ts . StringLiteral ) . text ;
741+ const text = this . escapeString ( ( node as ts . StringLiteral ) . text ) ;
718742 return `"${ text } "` ;
719743 case ts . SyntaxKind . TemplateExpression :
720744 return this . transpileTemplateExpression ( node as ts . TemplateExpression ) ;
@@ -889,13 +913,15 @@ export abstract class LuaTranspiler {
889913 }
890914
891915 public transpileTemplateExpression ( node : ts . TemplateExpression ) : string {
892- const parts = [ `"${ node . head . text } "` ] ;
916+ const parts = [ `"${ this . escapeString ( node . head . text ) } "` ] ;
893917 node . templateSpans . forEach ( span => {
894918 const expr = this . transpileExpression ( span . expression , true ) ;
919+ const text = this . escapeString ( span . literal . text ) ;
920+
895921 if ( ts . isTemplateTail ( span . literal ) ) {
896- parts . push ( `tostring(${ expr } ).."${ span . literal . text } "` ) ;
922+ parts . push ( `tostring(${ expr } ).."${ text } "` ) ;
897923 } else {
898- parts . push ( `tostring(${ expr } ).."${ span . literal . text } "` ) ;
924+ parts . push ( `tostring(${ expr } ).."${ text } "` ) ;
899925 }
900926 } ) ;
901927 return parts . join ( ".." ) ;
0 commit comments