Created
December 16, 2016 11:40
-
-
Save thoj/904c46efa960a06e038ff86de0dcdb81 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Example of reloading scripts on the fly with IronLua | |
// Test.lua here: https://gist.github.com/thoj/fee42fabc82b74e422bff3766cbcc8a8 | |
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; | |
while (true) | |
{ | |
RunScript(); | |
Thread.Sleep(100); | |
} | |
} | |
static void RunScript() | |
{ | |
if (scripts_changed) | |
{ | |
Console.WriteLine("Script Changed ..."); | |
try | |
{ | |
object old = null; | |
if (global != null && global["SomeObject"] != null) old = global["SomeObject"]; | |
lua = new Lua(); | |
var chunk = lua.CompileChunk("test.lua", new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default }); | |
global = lua.CreateEnvironment<LuaGlobal>(); | |
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