private void SetInitialState() { State = new NLua.Lua(); State.LoadCLRPackage(); State.DoString(@"import ('World','World.ToyWorldCore')"); State.DoString(@"import ('World','World.Lua')"); State["le"] = this; State["atlas"] = m_atlas; State.RegisterFunction("Help", typeof(LuaExecutor).GetMethod("Help")); if (m_atlas.Avatars.Count > 0) { AvatarCommander avatarCommander = new AvatarCommander(this, m_atlas); State["ac"] = avatarCommander; } AtlasManipulator atlasManipulator = new AtlasManipulator(m_atlas); State["am"] = atlasManipulator; State["lc"] = m_luaConsole; State.DebugHook += OnDebugHook; State.SetDebugHook(EventMasks.LUA_MASKLINE, 1000); }
public void Test() { using (var lua = new NLua.Lua()) { lua.LoadCLRPackage(); lua.DoString("luanet.load_assembly('mscorlib')"); lua.DoString("luanet.load_assembly('System.Windows.Forms')"); lua.DoString("a=luanet.import_type('System.Window.Forms.MessageBox')"); lua.DoString("a.Show('lua')"); Console.Read(); } }
private void OnDebugHook(object sender, DebugHookEventArgs e) { if (!ShouldStopScript) { return; } State.DoString(@"function TALuaScriptInternalStopHook(why) error ('" + "User interruption." + "'); end; debug.sethook (TALuaScriptInternalStopHook, '', 1);"); State.DoString("lc:Print(\"Core reset!\")"); ShouldStopScript = false; SetInitialState(); }
/// <summary> /// 执行lua脚本文件 /// </summary> /// <param name="luaFileName">脚本文件名</param> public void ExecuteFile(string luaFileName) { if (ExecutedFiles.Contains(luaFileName)) { return; } StreamReader SReader = new StreamReader(luaFileName, Encoding.UTF8); try { LuaState.DoString(SReader.ReadToEnd()); } catch (Exception ex) { throw new Exception("在" + luaFileName + "中发现异常:" + ex.Message); } SReader.Close(); ExecutedFiles.Add(luaFileName); }
public void Test() { using (var lua = new NLua.Lua()) { lua.LoadCLRPackage(); lua.RegisterFunction("Calc", null, typeof(Out_Test).GetMethod("Calc")); lua.DoString("a,b,c,e=Calc(10,2)"); double a = (double)lua["a"]; double b = (double)lua["b"]; double c = (double)lua["c"]; string e = (string)lua["e"]; lua.DoString("print('this is from lua print')"); Console.WriteLine("a:{0},b:{1},c:{2},e:{3}", a, b, c, e); Console.Read(); } }
protected override void DoModifyStator(TransientStepArgs args, FEMM femm) { // run script to update IA,IB,IC NLua.Lua lua_state = LuaHelper.GetLuaState(); String[] currentFormulas = { IA, IB, IC }; String[] circuitNames = { "A", "B", "C" }; lock (lockLua) { try { lua_state["step"] = args.step; lua_state["time"] = args.time; lua_state["omega"] = RotorSpeedRadSecond; for (int i = 0; i < currentFormulas.Length; i++) { double Ix = (double)lua_state.DoString("return " + currentFormulas[i])[0]; args.currents[circuitNames[i]] = Ix; } } catch (Exception ex) { log.Error("Lua error :" + ex.Message); } } base.DoModifyStator(args, femm); }
public (Action tritonAction, Action nluaAction) Benchmark_NoResults(Triton.Lua triton, NLua.Lua nlua) { void Triton() => triton.DoString("test = 0"); void NLua() => nlua.DoString("test = 0"); return(Triton, NLua); }
public void ProvideInfoToLua(NLua.Lua L) { L.LoadCLRPackage(); L.DoString("import ('The betrayer', 'TBAGW.Utilities') "); L["provisionState"] = this; L["provisionData"] = data; }
public (Action tritonAction, Action nluaAction) Benchmark_Results(Triton.Lua triton, NLua.Lua nlua) { void Triton() => triton.DoString("return 1, 2, 3, 4, 5"); void NLua() => nlua.DoString("return 1, 2, 3, 4, 5"); return(Triton, NLua); }
public void Run(string code) { using (NLua.Lua lua = new NLua.Lua()) { lua["lua_run_result_var"] = ""; try { lua.RegisterFunction("httpGet_row", null, typeof(Tools).GetMethod("HttpGet")); lua.RegisterFunction("httpPost_row", null, typeof(Tools).GetMethod("HttpPost")); lua.RegisterFunction("setData_row", null, typeof(Tools).GetMethod("LuaSetXml")); lua.RegisterFunction("getData_row", null, typeof(Tools).GetMethod("LuaGetXml")); lua.RegisterFunction("fileDownload", null, typeof(Tools).GetMethod("FileDownload")); lua.RegisterFunction("getImg", null, typeof(LuaApi).GetMethod("GetBitmap")); lua.RegisterFunction("setImgText", null, typeof(LuaApi).GetMethod("PutText")); lua.RegisterFunction("putImgBlock", null, typeof(LuaApi).GetMethod("putBlock")); lua.RegisterFunction("setImgImage", null, typeof(LuaApi).GetMethod("setImage")); lua.RegisterFunction("getImgDir", null, typeof(LuaApi).GetMethod("GetDir")); lua.RegisterFunction("getPath", null, typeof(LuaApi).GetMethod("GetPath")); lua.DoFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "lua/head.lua"); lua.DoString(Encoding.UTF8.GetBytes(headRun)); lua.DoString(Encoding.UTF8.GetBytes(code)); if (Tools.CharNum(lua["lua_run_result_var"].ToString(), "\n") > 40 || Tools.CharNum(lua["lua_run_result_var"].ToString(), "\r") > 40) { result = "行数超过了20行,限制一下吧"; } else if (lua["lua_run_result_var"].ToString().Length > 2000) { result = "字数超过了2000,限制一下吧"; } else { result = lua["lua_run_result_var"].ToString(); } } catch (Exception e) { string err = e.Message; int l = err.IndexOf("lua/"); if (l >= 0) { err = err.Substring(l); } result = "代码崩掉啦\r\n" + err; } } }
public (Action tritonAction, Action nluaAction) Benchmark_WriteObject(Triton.Lua triton, NLua.Lua nlua) { var tritonTable = triton.CreateTable(); var nluaTable = (NLua.LuaTable)nlua.DoString("return {}")[0]; void Triton() => tritonTable["test"] = new object(); void NLua() => nluaTable["test"] = new object(); return(Triton, NLua); }
public void Test() { using (var lua = new NLua.Lua()) { lua.LoadCLRPackage(); lua.RegisterFunction("Calc", null, typeof(ref_Test).GetMethod("Calc")); lua.DoString("a=1;b=2;c=3;d=4;e=nil;"); lua.DoString("result,c,d,e=Calc(a,b,c,d,e)"); double a = (double)lua["a"]; double b = (double)lua["b"]; double c = (double)lua["c"]; double d = (double)lua["d"]; string e = (string)lua["e"]; lua.DoString("print('this is from lua print')"); Console.WriteLine("a:{0},b:{1},c:{2},d:{3},e:{4}", a, b, c, d, e); Console.WriteLine(lua["result"]); Console.Read(); } }
public LuaExecutionEngine(string script) { if (script == null) { throw new ArgumentNullException("script"); } _script = script; _lua = new NLua.Lua(); _lua.LoadCLRPackage(); _lua.DoString(script); }
public (Action tritonAction, Action nluaAction) Benchmark_WriteStatic(Triton.Lua triton, NLua.Lua nlua) { triton.ImportType(typeof(TestClass)); nlua.DoString("TestClass = luanet.import_type('Triton.Benchmarks.Binding.FieldBenchmark+TestClass')"); var tritonFunction = triton.CreateFunction("TestClass.X = 0"); var nluaFunction = nlua.LoadString("TestClass.X = 0", "test"); void Triton() => tritonFunction.Call(); void NLua() => nluaFunction.Call(); return(Triton, NLua); }
/// <summary> /// 跑代码 /// </summary> /// <param name="s">代码</param> /// <returns>返回的结果</returns> public object[] DoString(string s) { try { return(lua.DoString(s)); } catch (Exception e) { ErrorEvent?.Invoke(lua, e.Message); throw new Exception(e.Message); } }
/// <summary> /// 初始化,加载全部接口 /// </summary> /// <param name="input">输入值,一般为匿名类</param> public LuaTask(object input = null) { lua = new NLua.Lua(); lua.State.Encoding = Encoding.UTF8; lua.LoadCLRPackage(); if (input != null) { lua["input"] = input;//传递输入值 } lua.DoString(sysCode); lua["@this"] = this;//自己传给自己 }
public (Action tritonAction, Action nluaAction) Benchmark_WriteReference(Triton.Lua triton, NLua.Lua nlua) { var tritonTable = triton.CreateTable(); var nluaTable = (NLua.LuaTable)nlua.DoString("return {}")[0]; var tritonFunction = triton.CreateFunction(""); var nluaFunction = nlua.LoadString("", "test"); void Triton() => tritonTable["test"] = tritonFunction; void NLua() => nluaTable["test"] = nluaFunction; return(Triton, NLua); }
public object[] DoString(string s) { try { return(lua.DoString(s)); } catch (Exception e) { Error(e); throw e; } }
public bool NLua(Parameter parameter) { using (NLua.Lua lua = new NLua.Lua()) { List <int> results = new List <int>(parameter.Statements.Length); foreach (string statement in parameter.Statements) { int result = Convert.ToInt32(lua.DoString("return " + statement)[0]); results.Add(result); } return(Assert(results, parameter.Sum)); } }
public bool NLua(Parameter parameter) { using (NLua.Lua lua = new NLua.Lua()) { StringBuilder statementBuilder = new StringBuilder() .AppendLine("return {") .AppendJoin("," + Environment.NewLine, parameter.Statements) .AppendLine("}"); NLua.LuaTable table = lua.DoString(statementBuilder.ToString())[0] as NLua.LuaTable; int[] results = table.Values.Cast <object>().Select(Convert.ToInt32).ToArray(); return(Assert(results, parameter.Sum)); } }
public void GetExists() { using (var lua = new NLua.Lua()) { lua.LoadCoroutineManager(); lua.DoString("function test() coroutine.yield(1) coroutine.yield(2) coroutine.yield(3) end " + "function test2() coroutine.yield(4) coroutine.yield(5) coroutine.yield(6) end"); lua.CreateCoroutine("test"); Assert.IsTrue(lua.ExistsCoroutine("test")); Assert.IsFalse(lua.ExistsCoroutine("test2")); lua.CreateCoroutine("test2"); Assert.IsTrue(lua.ExistsCoroutine("test")); Assert.IsTrue(lua.ExistsCoroutine("test2")); } }
public bool NLua(Parameter parameter) { using (NLua.Lua lua = new NLua.Lua()) { lua["n"] = parameter.Numbers; List <int> results = new List <int>(parameter.Numbers.Length); foreach (int number in parameter.Numbers) { int result = Convert.ToInt32(lua.DoString("return " + parameter.Statements[number])[0]); results.Add(result); } return(Assert(results, parameter.Sum)); } }
public (Action tritonAction, Action nluaAction) Benchmark_ReadReference(Triton.Lua triton, NLua.Lua nlua) { triton.DoString("test = function() end"); nlua.DoString("test = function() end"); void Triton() { var t = triton["test"]; } void NLua() { var t = nlua["test"]; } return(Triton, NLua); }
public (Action tritonAction, Action nluaAction) Benchmark_ReadNil(Triton.Lua triton, NLua.Lua nlua) { var tritonTable = triton.CreateTable(); var nluaTable = (NLua.LuaTable)nlua.DoString("return {}")[0]; void Triton() { var t = triton["test"]; } void NLua() { var t = nluaTable["test"]; } return(Triton, NLua); }
/// <summary> /// 在沙盒中运行代码,仅允许安全地运行 /// </summary> /// <param name="code"></param> /// <returns></returns> public static string RunSandBox(string code) { using var lua = new NLua.Lua(); try { lua.State.Encoding = Encoding.UTF8; lua.LoadCLRPackage(); lua["lua_run_result_var"] = "";//返回值所在的变量 lua.DoFile(Path + "lua/sandbox/head.lua"); lua.DoString(code); return(lua["lua_run_result_var"].ToString()); } catch (Exception e) { Log.Warn("lua沙盒错误", e.Message); return("运行错误:" + e.ToString()); } }
/// <summary> /// 在沙盒中运行代码,仅允许安全地运行 /// </summary> /// <param name="code"></param> /// <returns></returns> public static string RunSandBox(string code) { using var lua = new NLua.Lua(); try { lua.State.Encoding = Encoding.UTF8; lua.LoadCLRPackage(); lua["lua_run_result_var"] = "";//返回值所在的变量 lua.DoFile(Common.AppData.CQApi.AppDirectory + "lua/sandbox/main.lua"); lua.DoString(code); return(lua["lua_run_result_var"].ToString()); } catch (Exception e) { Common.AppData.CQLog.Warning("lua沙盒错误", e.Message); return("运行错误:" + e.ToString()); } }
/// <summary> /// 在沙盒中运行代码,仅允许安全地运行 /// </summary> /// <param name="code"></param> /// <returns></returns> public static string RunSandBox(string code) { using (var lua = new NLua.Lua()) { try { lua.State.Encoding = Encoding.UTF8; lua["lua_run_result_var"] = "";//返回值所在的变量 lua.DoFile(Common.AppDirectory + "lua/require/sandbox/head.lua"); lua.DoString(code); return(lua["lua_run_result_var"].ToString()); } catch (Exception e) { Common.CqApi.AddLoger(Sdk.Cqp.Enum.LogerLevel.Error, "沙盒lua脚本错误", e.ToString()); return("运行错误:" + e.ToString()); } } }
public CS_Script() { var fs = System.IO.Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory + py_path, "*.py", System.IO.SearchOption.AllDirectories); var code = ""; //for (int i=0;i<fs.Length;i++) //{ // var str= System.IO.File.ReadAllText(fs[i]) + "\r\n"; // CSScriptLib.CSScript.Evaluator.LoadCode(str); //} // var script = CSScriptLib.CSScript.Evaluator; // CSScriptLib.CSScript.GlobalSettings.AddSearchDir(System.AppDomain.CurrentDomain.BaseDirectory + cs_path); // ScriptRuntime pyRuntime = Python.CreateRuntime(); // dynamic py = pyRuntime.UseFile(fs[0]); NLua.Lua lua = new NLua.Lua(); lua.DoString("print('ffff')"); // script.SayHello("Hello World!"); // script.LoadCode("Console.WriteLine(new Class11().name);");//.GetType("Submission#0+EntryPoint").GetMethod("Start").Invoke(obj, null); }
public void Test() { using (var lua = new NLua.Lua()) { lua.State.Encoding = Encoding.UTF8; lua.LoadCLRPackage(); lua.DoString(@" import 'System.Windows.Forms'; frm=Form(); frm.Text='new form'; frm.Load:Add(function(sender,e) MessageBox.Show('窗体加载'); end) frm:ShowDialog(); "); Console.Read(); } }
public (Action tritonAction, Action nluaAction) Benchmark_ReadReference(Triton.Lua triton, NLua.Lua nlua) { var tritonTable = triton.CreateTable(); var nluaTable = (NLua.LuaTable)nlua.DoString("return {}")[0]; tritonTable["test"] = triton.CreateFunction(""); nluaTable["test"] = nlua.LoadString("", "test"); void Triton() { var t = tritonTable["test"]; } void NLua() { var t = nluaTable["test"]; } return(Triton, NLua); }
static void Main(string[] args) { NLua.Lua state = new NLua.Lua(); state.DoString(@" function ScriptFunc (val1, val2) if val1 > val2 then return val1 + 1 else return val2 - 1 end end "); var scriptFunc = state["ScriptFunc"] as NLua.LuaFunction; var res = scriptFunc.Call(3, 5).First(); // LuaFunction.Call will also return a array of objects, since a Lua function // can return multiple values Console.WriteLine(res); Console.ReadLine(); }
public void GetStatus() { using (var lua = new NLua.Lua()) { lua.LoadCoroutineManager(); lua.DoString("function test() coroutine.yield() coroutine.yield() coroutine.yield() end"); lua.CreateCoroutine("test"); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Suspended); bool isValid; lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Suspended); lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Suspended); lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Suspended); lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); } }
public void ResumeCoroutine() { using (var lua = new NLua.Lua()) { lua.LoadCoroutineManager(); lua.DoString("function test() local x = 1; coroutine.yield(x); return 2 end"); lua.CreateCoroutine("test"); bool isValid; object[] results = lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(isValid); Assert.IsTrue((int)(double)results[0] == 1); results = lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(isValid); Assert.IsTrue((int)(double)results[0] == 2); results = lua.ResumeCoroutine("test", out isValid); Assert.IsFalse(isValid); Assert.IsTrue((string)results[0] == "cannot resume dead coroutine"); } }
public void CleanDeadCoroutines() { using (var lua = new NLua.Lua()) { lua.LoadCoroutineManager(); lua.DoString("function test() return 1 end " + "function test2() coroutine.yield(1) return 2 end"); lua.CreateCoroutine("test"); lua.CreateCoroutine("test2"); lua.UpdateCoroutines(); lua.CleanDeadCoroutines(); Assert.IsTrue(!lua.ExistsCoroutine("test")); Assert.IsTrue(lua.ExistsCoroutine("test2")); lua.UpdateCoroutines(); lua.CleanDeadCoroutines(); Assert.IsTrue(!lua.ExistsCoroutine("test")); Assert.IsTrue(!lua.ExistsCoroutine("test2")); } }
public void ResumeCoroutineBis() { using (var lua = new NLua.Lua()) { lua.LoadCoroutineManager(); lua.DoString("function test() x = 1; coroutine.yield(x); return 2 end"); lua.CreateCoroutine("test"); LuaCoroutineResult result = lua.ResumeCoroutine("test"); Assert.IsTrue(result.IsValid); Assert.IsTrue((int)(double)result.Results[0] == 1); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Suspended); result = lua.ResumeCoroutine("test"); Assert.IsTrue(result.IsValid); Assert.IsTrue((int)(double)result.Results[0] == 2); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); result = lua.ResumeCoroutine("test"); Assert.IsFalse(result.IsValid); Assert.IsTrue(result.ErrorMessage == "cannot resume dead coroutine"); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); } }
public void RunCoroutine() { using (var lua = new NLua.Lua()) { lua.LoadCoroutineManager(); lua.DoString("function test() return 'truc', 2 end"); lua.CreateCoroutine("test"); bool isValid; object[] results = lua.ResumeCoroutine("test", out isValid); Assert.IsTrue(isValid); Assert.IsTrue((string)results[0] == "truc"); Assert.IsTrue((int)(double)results[1] == 2); } }
public void SleepCoroutine() { using (var lua = new NLua.Lua()) { lua.LoadCLRPackage(); lua.LoadCoroutineManager(); lua.DoString("function test() coroutine.manager.sleep(10, 'stopped 1') return 'hi' end " + "function test2() coroutine.manager.sleep(20, 'stopped 2') return 'hello' end "); lua.CreateCoroutine("test"); lua.CreateCoroutine("test2"); Dictionary<string, LuaCoroutineResult> results = lua.UpdateCoroutines(); Assert.IsTrue(results["test"].IsValid); Assert.IsTrue((string)results["test"].Results[0] == "stopped 1"); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Sleeping); Assert.IsTrue(results["test2"].IsValid); Assert.IsTrue((string)results["test2"].Results[0] == "stopped 2"); Assert.IsTrue(lua.StatusCoroutine("test2") == LuaCoroutineStatus.Sleeping); results = lua.UpdateCoroutines(10); Assert.IsTrue(results["test"].IsValid); Assert.IsTrue((string)results["test"].Results[0] == "hi"); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); Assert.IsTrue(results["test2"].IsValid); Assert.IsTrue(lua.StatusCoroutine("test2") == LuaCoroutineStatus.Sleeping); results = lua.UpdateCoroutines(10); Assert.IsFalse(results["test"].IsValid); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); Assert.IsTrue(results["test2"].IsValid); Assert.IsTrue((string)results["test2"].Results[0] == "hello"); Assert.IsTrue(lua.StatusCoroutine("test2") == LuaCoroutineStatus.Dead); } }
public void UpdateCoroutines() { using (var lua = new NLua.Lua()) { lua.LoadCLRPackage(); lua.LoadCoroutineManager(); lua.DoString("function test() return 'hi' end " + "function test2() coroutine.yield() return true end " + "function test3() return 3,4 end"); lua.CreateCoroutine("test"); lua.CreateCoroutine("test2"); lua.CreateCoroutine("test3"); Dictionary<string, LuaCoroutineResult> results = lua.UpdateCoroutines(); Assert.IsTrue(results["test"].IsValid); Assert.IsTrue((string)results["test"].Results[0] == "hi"); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); Assert.IsTrue(results["test2"].IsValid); Assert.IsTrue(lua.StatusCoroutine("test2") == LuaCoroutineStatus.Suspended); Assert.IsTrue(results["test3"].IsValid); Assert.IsTrue((int)(double)results["test3"].Results[0] == 3); Assert.IsTrue((int)(double)results["test3"].Results[1] == 4); Assert.IsTrue(lua.StatusCoroutine("test3") == LuaCoroutineStatus.Dead); results = lua.UpdateCoroutines(); Assert.IsFalse(results["test"].IsValid); Assert.IsTrue(lua.StatusCoroutine("test") == LuaCoroutineStatus.Dead); Assert.IsTrue(results["test2"].IsValid); Assert.IsTrue((bool)results["test2"].Results[0]); Assert.IsTrue(lua.StatusCoroutine("test2") == LuaCoroutineStatus.Dead); Assert.IsFalse(results["test3"].IsValid); Assert.IsTrue(lua.StatusCoroutine("test3") == LuaCoroutineStatus.Dead); } }