-
-
Save jochemstoel/d3f878fa20bbe2bbc5ee9d32aca9d263 to your computer and use it in GitHub Desktop.
Example REPL | not the best way to write a REPL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.ClearScript; | |
using Microsoft.ClearScript.V8; | |
namespace v8repl | |
{ | |
class REPL | |
{ | |
/* v8 engine outside main loop */ | |
private V8ScriptEngine v8 = new V8ScriptEngine(); | |
private bool running = false; /* */ | |
/* keep reading input from stdin until running = false */ | |
public void Start() | |
{ | |
running = true; | |
while (running) | |
{ | |
string line = Console.ReadLine(); | |
if (line.Equals("kill")) | |
{ | |
running = false; /* causes this while loop to stop */ | |
} | |
else { | |
Run(line); | |
} | |
} | |
} | |
/* method to read and evaluate JavaScript file */ | |
public void LoadFile(string inputFile) | |
{ | |
v8.Evaluate( | |
System.IO.File.ReadAllText(inputFile) | |
); | |
} | |
/* safely evaluate code like we did before */ | |
public void Run(string line) | |
{ | |
try | |
{ | |
v8.Evaluate(line); | |
} | |
catch (System.Exception e) | |
{ | |
Console.Error.WriteLine(e.Message); | |
} | |
} | |
/* this allows us to get current instance */ | |
public V8ScriptEngine GetInstance() | |
{ | |
return v8; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment