增加lua的支持

This commit is contained in:
Longfeng Qin 2024-12-11 06:05:23 +08:00
parent f26c11ac73
commit 48dbe8785c
3 changed files with 90 additions and 0 deletions

View File

@ -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();
}
}
}

View File

@ -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++)

View File

@ -313,6 +313,7 @@
<Compile Include="Json\JsonRead.cs" />
<Compile Include="Json\QuestJson.cs" />
<Compile Include="Logger.cs" />
<Compile Include="LuaEngine\LuaEngine.cs" />
<Compile Include="Models\BattleStats.cs" />
<Compile Include="Models\BlockInfo.cs" />
<Compile Include="Models\CharacterAdditionalStruct.cs" />