jeudi 24 mai 2018

Multiline batch-like string parser using for-loop didn't work correctly

I tried to create a batch-like parser with JavaScript for-loop and if-statement combination. I'd like to make the for-loop to stop when it reaches pause line until I re-call the function, and if the line is not pause then it can continue to execute the parsed string. I used ES2015 back-ticked multi-line to create the multi line string to be parsed by the parser. This is my code:

var currentLine = 0


function parseBatch(batchString){
  var line = batchString.split("\n")
    for(a=currentLine;a<line.length;a++){ //using currentLine as start to determine where last line to be executed
      var args = line[a].split(" ");
      if(args[0]==="pause"){
        currentLine = a+1 //avoiding still at 'pause' line
        break; //stop the running loop
      }else{
        //currentLine = a+1 // I think it will just skip next line
        executeCommand(args) //passing the argument to other function and continue
      }
   }
return "Finish"
}

var testBatch = `echo Start
echo Testing the Parser
echo Second line
pause
echo After pause
echo Fourth line
pause
`
parseBatch(testBatch)

NB: echo will execute console.log function

However, when trying to run it, it always stuck at echo Second line. or when I try to uncomment the currentLine = a+1 at else block, the function will skip next batch line and will back to random line before the currently processed line when it reaches end of multi line string (I don't know, it really occurs), and sometime will produce an infinite-loop.

Can someone fix my code or tell me where the wrong is?

I wasn't in hurry however.

Aucun commentaire:

Enregistrer un commentaire