Allow for evaling statements in REPL too
authorRyan Dahl <ry@tinyclouds.org>
Sun, 2 Jan 2011 05:04:13 +0000 (21:04 -0800)
committerRyan Dahl <ry@tinyclouds.org>
Sun, 2 Jan 2011 05:05:23 +0000 (21:05 -0800)
lib/repl.js

index 04f8696..8e9c036 100644 (file)
@@ -104,12 +104,25 @@ function REPLServer(prompt, stream) {
     if (!skipCatchall) {
       // The catchall for errors
       try {
-        self.buffered_cmd += '\n' + cmd;
+        self.buffered_cmd += cmd + '\n';
         // This try is for determining if the command is complete, or should
         // continue onto the next line.
         try {
-          // Use evalcx to supply the global context
-          var ret = evalcx('(' + self.buffered_cmd + ')', context, 'repl');
+          // We try to evaluate both expressions e.g.
+          //  '{ a : 1 }'
+          // and statements e.g.
+          //  'for (var i = 0; i < 10; i++) console.log(i);'
+
+          var ret;
+          try {
+            // First we attempt to eval as expression with parens.
+            // This catches '{a : 1}' properly.
+            ret = evalcx('(' + self.buffered_cmd + ')', context, 'repl');
+          } catch (e)  {
+            // Now as statement without parens.
+            ret = evalcx(self.buffered_cmd, context, 'repl');
+          }
+
           if (ret !== undefined) {
             context._ = ret;
             self.stream.write(exports.writer(ret) + '\n');