Unity XLua(三)C#访问Lua脚本中全局方法

访问Lua脚本中全局方法

Lua脚本

function add(a,b)
	return a + b
end

 C#访问

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

public class Test : MonoBehaviour
{
    LuaEnv lua;

    [CSharpCallLua]
    public delegate int Add(int a,int b);
    void Start()
    {
        lua = new LuaEnv();

        //加载Lua
        lua.AddLoader(LoadLua);
        lua.DoString("require 'TestLua'");

        //访问Lua脚本中的function
        Add add = lua.Global.Get("add");
        Debug.Log(add(2, 5));
    }

    byte[] LoadLua(ref string file)
    {
        Debug.Log(file);

        string slua = File.ReadAllText(Application.dataPath + "/Lua/" + file + ".lua");
        byte[] bytes = new UTF8Encoding().GetBytes(slua);

        return bytes;
    }

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

Lua脚本

function num(a,b)
	return a+b,a-b
end

C#访问

方式一:

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

public class Test : MonoBehaviour
{
    LuaEnv lua;

    [CSharpCallLua]
    public delegate int Num(int a, int b,out int c);
    void Start()
    {
        lua = new LuaEnv();

        //加载Lua
        lua.AddLoader(LoadLua);
        lua.DoString("require 'TestLua'");

        //访问Lua脚本中的function
        Num num = lua.Global.Get("num");
        int n2;
        int n1 = num(5,2,out n2);
        Debug.Log(n1);
        Debug.Log(n2);
    }

    byte[] LoadLua(ref string file)
    {
        Debug.Log(file);

        string slua = File.ReadAllText(Application.dataPath + "/Lua/" + file + ".lua");
        byte[] bytes = new UTF8Encoding().GetBytes(slua);

        return bytes;
    }

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

方式二:

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

public class Test : MonoBehaviour
{
    LuaEnv lua;

    void Start()
    {
        lua = new LuaEnv();

        //加载Lua
        lua.AddLoader(LoadLua);
        lua.DoString("require 'TestLua'");

        //访问Lua脚本中的function
        LuaFunction lf = lua.Global.Get("num");
        object[]objects = lf.Call(8,2);
        Debug.Log(objects[0]);
        Debug.Log(objects[1]);
    }

    byte[] LoadLua(ref string file)
    {
        Debug.Log(file);

        string slua = File.ReadAllText(Application.dataPath + "/Lua/" + file + ".lua");
        byte[] bytes = new UTF8Encoding().GetBytes(slua);

        return bytes;
    }

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

你可能感兴趣的:(Unity,Lua)