Several ways for Unity to call Lua (details)

I am also a newbie and would like to express my opinion on Lua. In the process of learning Lua, the Lua called by Unity can call the corresponding properties, methods, and methods of the module (which is equivalent to the class in C#) through delegates, structures, classes, and interfaces (if There are other better ways, please explain to me).

//结构体
public struct Son
{
    public int Id;
    public string s;

}
//类
public class Son1
{
    public int Id;
    public string s;
}
//接口
public interface Son2
{
    public int Id { get; set; }
    public string s { get; set; }
    public void Func();
    
}
//委托
public delegate int id;
public delegate int Obj(object a, object b);

In my opinion, the use of interfaces should be the most useful among these four methods. My recommendation is also to use interfaces to retrieve. When I use other methods to get the methods in the module, some small bugs will appear, so if you want to get the methods in the class, I recommend you to use interfaces here. Other small data can be obtained most conveniently using structures.
 

Use of interfaces: Get methods in classes

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;

/*
*创建者:
*创建时间:
*描述:
*版本:
*/
[CSharpCallLua]//一定要添加特性,里面的属性名称和方法名称也必须和Lua里面的相同
public interface Open
{
    public string Id { get; set; }
    public string Pwd { get; set; }
    void GetUI();
}

public class Te: MonoBehaviour
{
    LuaEnv lua;
    Open o;
    void Start()
    {
        lua = new LuaEnv();
        lua.AddLoader(FileLoading);//加载器
        lua.DoString("require('M')");//获取
        o = lua.Global.Get<Open>("A");
        print(o.Id);
        print(o.Pwd);
        o.GetUI();

        
    }
    byte[] FileLoading(ref string name)//读文件的方式读取Lua内容
    {
        
        string s = Application.dataPath + "/Lua/" + name + ".lua";
        return File.ReadAllBytes(s);
    }

    void OnDestory()
    {
        lua.Dispose();
    }
}

Lua part:


A={
	Id=1001,
	Pwd='密码',
	GetUI=function()
		print("获取到类里面的方法")
	end
}

Output result: 

 Delegate acquisition method

[CSharpCallLua]//委托获取,不用特性也可以
public delegate void D();
public class Te : MonoBehaviour
{
    LuaEnv lua;
    void Start()
    {
        lua = new LuaEnv();
        lua.AddLoader(FileLoading);
        lua.DoString("require('M')");
        D d = lua.Global.Get<D>("Out");
        d();
      

    }
    byte[] FileLoading(ref string name)
    {

        string s = Application.dataPath + "/Lua/" + name + ".lua";
        return File.ReadAllBytes(s);
    }

    void OnDestory()
    {
        lua.Dispose();
    }

Lua script:

function Out()
	print("外面的方法")
end

Output result:

 

Guess you like

Origin blog.csdn.net/m0_71624363/article/details/129960557
Recommended