C#中运行lua脚本文件,在脚本文件中调用C#函数
1、创建NetFramwork窗体应用程序
2、添加Lua引用
将lua51.dll、LuaInterface.dll库拷贝到应用程序的debug目录下;
给项目添加LuaInterface引用。
3、准备lua文件
将lua_test.lua文件放在Script目录下,其内容为:
function MyNum(i)
s = MyStr("Hello")
return i,s
end
4、创建测试函数MyStr
namespace LuaWinApp
{
public class Test
{
public string MyStr(string s)
{
return s + "World!";
}
}
}
5、创建测试界面
测试界面包括一个按钮,点击按钮运行脚本
namespace LuaWinApp
{
public partial class Form1 : Form
{
public Lua lua = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
lua = new Lua();
Test test = new Test();
lua.RegisterFunction("MyStr", test, test.GetType().GetMethod("MyStr"));
string path = System.Windows.Forms.Application.StartupPath+ "\\Script\\lua_test.lua";
//string path1 = Directory.GetCurrentDirectory();
lua.DoFile(path);
//加载乱文件后,使用GetFunction获取函数,再调用Call执行(传参数)
Object[] objs = lua.GetFunction("MyNum").Call(100);
//Call函数的返回值为一个Object数组
foreach (Object obj in objs)
{
//Console.WriteLine(obj);
System.Diagnostics.Debug.WriteLine(obj);
}
}
}
}
6、运行会提示错误,需更改App.config文件
更改前
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
</configuration>
更改后
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>
运行效果