diff --git a/Server/LuaEngine/LuaEngine.cs b/Server/LuaEngine/LuaEngine.cs new file mode 100644 index 0000000..5e8348f --- /dev/null +++ b/Server/LuaEngine/LuaEngine.cs @@ -0,0 +1,70 @@ +using NLua; +using System; + +namespace PSO2SERVER.LuaEngine +{ + public class LuaScriptEngine + { + private Lua lua; + + public LuaScriptEngine() + { + // 初始化 LuaEngine 解释器 + lua = new Lua(); + } + + // 执行 LuaEngine 脚本 + public void ExecuteScript(string script) + { + try + { + // 执行传入的 LuaEngine 脚本 + lua.DoString(script); + } + catch (Exception ex) + { + Console.WriteLine("Error executing LuaEngine script: " + ex.Message); + } + } + + // 执行并获取 LuaEngine 脚本结果 + public object ExecuteScriptWithResult(string script) + { + try + { + // 执行 LuaEngine 脚本并返回结果 + return lua.DoString(script)[0]; + } + catch (Exception ex) + { + Console.WriteLine("Error executing LuaEngine script: " + ex.Message); + return null; + } + } + + // 将 C# 对象传递给 LuaEngine 环境 + public void SetGlobalVariable(string name, object value) + { + lua[name] = value; + } + + // 获取 LuaEngine 环境中的全局变量 + public object GetGlobalVariable(string name) + { + return lua[name]; + } + + // 使用 MethodBase 注册方法 + public void RegisterFunction(string luaFunctionName, object obj, string methodName) + { + var methodInfo = obj.GetType().GetMethod(methodName); + lua.RegisterFunction(luaFunctionName, obj, methodInfo); + } + + // 清理 LuaEngine 解释器 + public void Dispose() + { + lua.Dispose(); + } + } +} diff --git a/Server/Program.cs b/Server/Program.cs index adb299a..0b92a6c 100644 --- a/Server/Program.cs +++ b/Server/Program.cs @@ -18,6 +18,7 @@ using Newtonsoft.Json; using PSO2SERVER.Zone; using PSO2SERVER.Json; using PSO2SERVER.Models; +using NLua; namespace PSO2SERVER { @@ -97,6 +98,24 @@ namespace PSO2SERVER //JsonTest.JsonReadTest(); + //using (var state = new LuaEngine()) + //{ + // //Retrieving LuaEngine functions: + // state.DoString(@"function ScriptFunc (val1, val2) + // if val1 > val2 then + // return val1 + 1 + // else + // return val2 - 1 + // end + // end + // "); + // var scriptFunc = state["ScriptFunc"] as LuaFunction; + // var funcRes = scriptFunc.Call(3, 5).First(); + // Console.WriteLine($"Func result:{funcRes}"); + + // Console.ReadKey(); + //} + try { for (var i = 0; i < args.Length; i++) diff --git a/Server/Server.csproj b/Server/Server.csproj index 1a87ed7..20425b8 100644 --- a/Server/Server.csproj +++ b/Server/Server.csproj @@ -313,6 +313,7 @@ +