C#与Lua相互调用

作者:追风剑情 发布于:2019-7-1 16:25 分类:C#

这里使用NLua库

GitHub https://github.com/NLua/NLua

Lua教程 https://www.runoob.com/lua/lua-tutorial.html

111.png

222222.png

示例代码


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//https://github.com/NLua/NLua
using NLua;

namespace LuaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Lua lua = new Lua())
            {
                Console.WriteLine("C#访问Lua变量");
                lua.State.Encoding = Encoding.UTF8;
                lua.DoString("x=5+3");
                double x = (double)lua["x"];
                Console.WriteLine("x="+ x);

                Console.WriteLine(System.Environment.NewLine);
                Console.WriteLine("C#访问Lua函数");
                lua.DoString(@"
	            function ScriptFunc (val1, val2)
		            if val1 > val2 then
			            return val1 + 1
		            else
			            return val2 - 1
		            end
	            end
	            ");
                LuaFunction scriptFunc = lua["ScriptFunc"] as LuaFunction;
                //Call函数返回的是一个数组,需要取第1个值
                long res = (long)scriptFunc.Call(3, 5).First();
                Console.WriteLine("res="+res);

                Console.WriteLine(System.Environment.NewLine);
                Console.WriteLine("Lua访问C#");
                SomeClass obj = new SomeClass("Param");
                lua["obj"] = obj;
                lua.LoadCLRPackage();
                lua.DoString(@" 
                    import ('LuaTest', 'LuaTest')
			        import ('System.Web') 
                    obj2 = SomeClass()
                    local res1 = obj:Func1()
	                local res2 = obj2:AnotherFunc (10, 'hello')
                    local res4 = SomeClass.StaticMethod(4)
                    local res5 = obj.MyProperty
                    print('res1', res1)
                    print('res2', res2)
                    print('res4', res4)
                    print('res5', res5)
                ");

                Console.ReadKey();
            }
        }
    }

    public class SomeClass
    {
        public string MyProperty { get; private set; }

        public SomeClass(string param1 = "defaulValue")
        {
            MyProperty = param1;
        }

        public int Func1()
        {
            return 32;
        }

        public string AnotherFunc(int val1, string val2)
        {
            return "Some String";
        }

        public static string StaticMethod(int param)
        {
            return "Return of Static Method";
        }
    }
}


运行测试

3333.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号