C#中运行lua脚本文件,在脚本文件中调用C#函数

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>

运行效果
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大浪淘沙胡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值