Skip to content

Instantly share code, notes, and snippets.

@jochemstoel
Created January 7, 2018 17:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jochemstoel/d3f878fa20bbe2bbc5ee9d32aca9d263 to your computer and use it in GitHub Desktop.
Save jochemstoel/d3f878fa20bbe2bbc5ee9d32aca9d263 to your computer and use it in GitHub Desktop.
Example REPL | not the best way to write a REPL
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