Lua热更新学习 lua与C#的互相调用

版权声明:转载 请说明 https://blog.csdn.net/qq2512667/article/details/83502947

在 热跟新中 只需要 写好  解析Lua 脚本的代码

然后c#代码 不需要变动 ,只需要修改 Lua脚本就好了 

通过Lua 脚本控制 游戏逻辑

 

Lua 和C#中的类型 的对应

几个重要的  

      lua          c#

nil           null

table       LuaInterface.LuaTable

function  LuaInterface.LuaTable

在C#里 需要 引入LuaInterface

在LuaInterface 程序集里

有连个 会 比较 常用的 方法

扫描二维码关注公众号,回复: 4259331 查看本文章

DoFile( string fileName)可以在C#中  执行 Lua文件

DoString(sting chunk ) 可以执行Lua的 代码 。

   static void Main(string[] args)
        {
            Lua lua = new Lua();

           // lua.DoFile("script.lua");
            lua.DoString("num=2");
            lua.DoString("str='a string'");

            object[] objs = lua.DoString("return num,str");
            foreach (object obj in objs)
            {
                Console.WriteLine(obj.ToString());
            }
        } 

luaInterface 还提供 了一个方法     可以把c#的方法 注册进Lua的一个全局方法

//把一个 类中的 普通 方法 注册进去

lua.RegisterFunction("NormalMethod",obj,obj.GetType().GetMethod("NormalMethod"))

lua.DoString("NormalMethod")

//把一个 类中的静态方法 注册进去

 lua.RegisterFunction("StaticMethod",null,typeof(ClassName).getMethod("StaticMethod"))

lua.DoString("StaticMethod")

在lua中  想要调用C#中方法,或者访问C#中的属性 字段时, 可以通过几个步骤来访问

namespace TestLuaInterface
{
    class Program
    {
        public string name = "Jack";
        public int age = 18;
        public void Say()
        {
            Console.WriteLine($"Im {name}");
        }
        public void StringLength(string str,out int count)
        {
            Console.WriteLine(str);
            count = str.Length;
        }
        public void StringRef(string str, ref int count)
        {
            Console.Write(str);
            count = str.Length;
        }
        
        static void Main(string[] args)
        {
            Lua lua = new Lua();

            Program p = new Program();
            lua.RegisterFunction("Say", p, p.GetType().GetMethod("Say"));

            lua.RegisterFunction("StaticMethod", null, typeof(Program).GetMethod("StaticMethod"));

            lua.DoString("Say()");
            lua.DoString("StaticMethod()");
            lua.DoFile("script.lua");
           // lua.DoString("num=2");
           // lua.DoString("str='a string'");

           // object[] objs = lua.DoString("return num,str");
           // foreach (object obj in objs)
           // {
               // Console.WriteLine(obj.ToString());
           // }
        } 
    }
}

在lua中 由luanet在建立和C# 中的访问 

  1.  require "luanet"   --引入 库  加载CLR的类型,实例化CLR对象
  2. luanet.load_assembly("TestLuaInterface") --加载程序集
  3. Program= luanet_import_type(TestLuaInterface.Progran) -- 加载 类型
  4. Program1=  Program() --lua 中实例化  不需要 用new 关键字
  5. Program1:Say()   --访问 类中的方法
  6. Program1.name   --访问 字段

猜你喜欢

转载自blog.csdn.net/qq2512667/article/details/83502947