71 lines
1.8 KiB
C#
71 lines
1.8 KiB
C#
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();
|
|
}
|
|
}
|
|
}
|