Skip to content

Instantly share code, notes, and snippets.

@thoj
Created December 19, 2016 13:03
Show Gist options
  • Save thoj/52057dd7331ab776e3ce63e0950856b1 to your computer and use it in GitHub Desktop.
Save thoj/52057dd7331ab776e3ce63e0950856b1 to your computer and use it in GitHub Desktop.
// Example of reloading scripts on the fly with IronLua
using System;
using Neo.IronLua;
using System.Threading;
using System.IO;
namespace LuaTest
{
class SomeObject
{
public string data = "somedata";
public int counter = 0;
public SomeObject (string data)
{
this.data = data;
}
}
class Program
{
private static bool scripts_changed = true;
private static Lua lua;
private static LuaGlobal global;
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.lua";
watcher.Changed += (o, e) => { scripts_changed = true; };
watcher.EnableRaisingEvents = true;
lua = new Lua();
global = lua.CreateEnvironment<LuaGlobal>();
while (true)
{
RunScript();
Thread.Sleep(100);
}
}
static void RunScript()
{
//if (scripts_changed)
if (true)
{
Console.WriteLine("Script Changed ...");
try
{
object old = null;
if(global["SomeObject"] != null) old = global["SomeObject"];
var chunk = lua.CompileChunk("test.lua", new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default });
global.DoChunk(chunk);
if (old == null) global.CallMember("INIT");
else global["SomeObject"] = old;
}
catch (LuaParseException e)
{
Console.WriteLine("Parse Error: {0} Line: {1:N0} Col: {2:N0} in {3}", e.Message, e.Line, e.Column, e.FileName);
Thread.Sleep(1000);
return;
}
catch (Exception e)
{
var d = LuaExceptionData.GetData(e); // get stack trace
Console.WriteLine("Exception: {0}", e.Message);
Console.WriteLine("Exception: {0}", d.StackTrace);
Thread.Sleep(1000);
return;
}
finally
{
global["Ready"] = false;
scripts_changed = false;
}
}
global["Ready"] = true;
try
{
global.CallMember("MAIN");
}
catch (Exception e)
{
var d = LuaExceptionData.GetData(e); // get stack trace
Console.WriteLine("Runtime Error: {0}", e.Message);
Console.WriteLine("Runtime Error: {0}", d.StackTrace);
Thread.Sleep(1000);
scripts_changed = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment