首页 > 编程语言 >xlua - c#访问lua函数

xlua - c#访问lua函数

时间:2024-02-28 22:23:21浏览次数:27  
标签:Get c# Global xlua lua LuaEnv print public out

lua代码

Assets/Lua/Test1.lua.txt

function IntParam(p)
    print("~~~~~ IntParam")
    print(type(p), p)
    print("~~~~~")
    return p
end

function Vec3Param(p)
    print("~~~~~ Vec3Param")
    print(type(p), p.x, p.y, p.z)
    print("~~~~~")
    return p
end

function EnumParam(p)
    print("~~~~~ EnumParam")
    print(type(p), p)
    print("~~~~~")
    return p
end

function ArrayParam(p)
    print("~~~~~ ArrayParam")
    print(type(p), p.Length)
    for i=0,p.Length-1 do
        print(i, p[i])
    end
    print("~~~~~")
    return p
end

function RefOutParam(p1, p2)
    print("~~~~~ RefOutParam")
    print(type(p1), p1, type(p2), p2)
    return 1, 2, 3
end

function MyStructParam(p)
    print("~~~~~ ArrayParam")
    print(type(p), p.str, p.value.i, p.value.f)
    print("~~~~~")
    return p
end

function ReturnTable()
    return { a = 1, b =2 }
end

 

1, 将lua函数映射为c#委托的方式

委托部分

[CSharpCallLua]
public delegate int IntParamDelegate(int p);

[CSharpCallLua]
public delegate int Vec3ParamDelegate(Vector3 p);

[CSharpCallLua]
public delegate int EnumParamDelegate(StringSplitOptions opts);

[CSharpCallLua]
public delegate Array ArrayParamDelegate(Array arr);

[CSharpCallLua]
public delegate int RefOutParamDelegate(ref int p1, out int p2);

[GCOptimize]
[LuaCallCSharp]
public struct MyStruct1
{
    public int i;
    public float f;
}

[GCOptimize]
[LuaCallCSharp]
public struct MyStruct2
{
    public MyStruct1 value;
    public string str;
}

[CSharpCallLua]
public delegate MyStruct2 MyStructParamDelegate(MyStruct2 p);

映射并调用代码

public class Test1 : MonoBehaviour
{
    private LuaEnv m_LuaEnv;

    private IntParamDelegate m_IntParamDelegate;
    private Vec3ParamDelegate m_Vec3ParamDelegate;
    private EnumParamDelegate m_EnumParamDelegate;
    private ArrayParamDelegate m_ArrayParamDelegate;
    private RefOutParamDelegate m_RefOutParamDelegate;
    private MyStructParamDelegate m_MyStructParamDelegate;

    public Func<int, int> m_IntParamFunc;

    void Start()
    {
        m_LuaEnv = new LuaEnv();
        m_LuaEnv.AddLoader((ref string filePath) =>
        {
            filePath = filePath.Replace('.', '/');
            filePath = $"Assets/{filePath}.lua.txt";
            var txtAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(filePath);
            return Encoding.UTF8.GetBytes(txtAsset.text);
        });

        m_LuaEnv.DoString("require('Lua.Test1')");

        m_LuaEnv.Global.Get("IntParam", out m_IntParamDelegate);
        m_LuaEnv.Global.Get("IntParam", out m_IntParamFunc);
        m_LuaEnv.Global.Get("Vec3Param", out m_Vec3ParamDelegate);
        m_LuaEnv.Global.Get("EnumParam", out m_EnumParamDelegate);
        m_LuaEnv.Global.Get("ArrayParam", out m_ArrayParamDelegate);
        m_LuaEnv.Global.Get("RefOutParam", out m_RefOutParamDelegate);
        m_LuaEnv.Global.Get("MyStructParam", out m_MyStructParamDelegate);
    }

    void OnDestroy()
    {
        if (null != m_LuaEnv)
        {
            //必须先置为null, 否则Dispose报错
            m_IntParamDelegate = null;
            m_IntParamFunc = null;
            m_Vec3ParamDelegate = null;
            m_EnumParamDelegate = null;
            m_ArrayParamDelegate = null;
            m_RefOutParamDelegate = null;
            m_MyStructParamDelegate = null;
            m_LuaEnv.Dispose();
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            m_IntParamDelegate(1);
            m_IntParamFunc(2);
            m_Vec3ParamDelegate(new Vector3(1, 2, 3));
            m_EnumParamDelegate(StringSplitOptions.RemoveEmptyEntries);
            m_ArrayParamDelegate(new int[] { 1, 2, 3 });
            int i1 = 0;
            m_RefOutParamDelegate(ref i1, out var i2); //lua中的第1个是本身返回值, 第2个为ref参数, 第3个为out参数
            Debug.Log($"i1:{i1}, i2:{i2}");

            var myStruct = new MyStruct2();
            myStruct.str = "hello";
            myStruct.value.i = 10;
            myStruct.value.f = 2.3f;
            m_MyStructParamDelegate(myStruct);
        }
    }

}

 

 

2, LuaFunction类方式

public class Test1 : MonoBehaviour
{
    private LuaEnv m_LuaEnv;

    public LuaFunction m_LuaFuncIntParam;
    public LuaFunction m_LuaFuncVec3Param;
    public LuaFunction m_LuaFuncArrayParam;
    public LuaFunction m_LuaFuncRefOutParam;
    public LuaFunction m_LuaFuncMyStructParam;

    void Start()
    {
        m_LuaEnv = new LuaEnv();
        m_LuaEnv.AddLoader((ref string filePath) =>
        {
            filePath = filePath.Replace('.', '/');
            filePath = $"Assets/{filePath}.lua.txt";
            var txtAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(filePath);
            return Encoding.UTF8.GetBytes(txtAsset.text);
        });

        m_LuaEnv.DoString("require('Lua.Test1')");

        m_LuaEnv.Global.Get("IntParam", out m_LuaFuncIntParam);
        m_LuaEnv.Global.Get("Vec3Param", out m_LuaFuncVec3Param);
        m_LuaEnv.Global.Get("ArrayParam", out m_LuaFuncArrayParam);
        m_LuaEnv.Global.Get("RefOutParam", out m_LuaFuncRefOutParam);
        m_LuaEnv.Global.Get("MyStructParam", out m_LuaFuncMyStructParam);
    }

    void OnDestroy()
    {
        if (null != m_LuaEnv)
        {
            m_LuaEnv.Dispose();
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            m_LuaFuncIntParam.Func<int, int>(3);
            m_LuaFuncVec3Param.Func<Vector3, Vector3>(new Vector3(5, 6, 7));
            m_LuaFuncArrayParam.Func<Array, Array>(new string[] { "a", "b", "c" });
            var results = m_LuaFuncRefOutParam.Call(0);
            foreach (var item in results)
            {
                Debug.Log($"{item.GetType().Name}:{item}");
            }

            var myStruct = new MyStruct2();
            myStruct.str = "hello";
            myStruct.value.i = 10;
            myStruct.value.f = 2.3f;
            m_LuaFuncMyStructParam.Func<MyStruct2, MyStruct2>(myStruct);

            var luaFunc = m_LuaEnv.Global.Get<LuaFunction>("ReturnTable");
            results = luaFunc.Call();
            foreach (var item in results)
            {
                Debug.Log($"{item.GetType().Name}:{item}");
            }
        }
    }

}

 

 

参考

xLua-C#访问lua中的全局function_fdelegate xlua-CSDN博客

 

标签:Get,c#,Global,xlua,lua,LuaEnv,print,public,out
From: https://www.cnblogs.com/sailJs/p/18037210

相关文章

  • 454. 四数相加 II C
    自己写了一个hash表。原来学过的数据结构关于hash的那章还是有实际用的,不是书架子。typedefstructnode{intsum;intcount;structnode*repeatnext;}hash;voidinit_hashtable(hashh[]){for(inti=0;i<127;i++){h[i].sum=0;h[i].......
  • CSP2023 游寄
    你不会T1你会什么题啊,你一题不会你打个锤子啊——老KDay-2最后一场模拟赛,T3被卡常挂了50,T4没读懂题直接爆0。3场模拟赛一崩到底,喜提倒数,寄。Day-1上午动员大会,连线到了lk,真好。然后pty讲了些小技巧,模拟赛中经常因为奇怪错误挂分的我被反复鞭尸。下午和几个巨......
  • CSP-S总结
    时间分配:T1:30min,T3:1.5h,T4:1.5h,剩下交给T2。T1:签到题,秒了。做法:直接枚举密码状态暴力校验。估分:100(话说某人貌似看到我10min开始测样例心态直接爆炸了)T2:感觉难度绿里绿气的,但一直不会。直接写了个区间dp,然后想到枚举左端点向右扩展,用栈维护,拿到50。然后一直感觉栈的......
  • centos中无法访问外网排除点
    1,查看网卡信息一般在Centos中网卡所在位置是/etc/sysconfig/network-scripts/目录下,找到对应网卡查看即可2,查看防火墙信息查看防火墙状态firewall-cmd--state如果防火墙状态是runing,则建议关闭systemctlstopfirewalld,永久关闭开机不启动systemctldisablefirewalld......
  • RHCE高级权限和文件系统
    一:高级用户组和用户权限1:密码策略1:含义密码策略就是设置密码的一些属性,如什么时候密码过期等修改的就是这个配置文件/etc/shadow这里面的参数user2:!!:19768:0:99999:7:::第一个字段:用户名第二个字段:密码占位符,!!表示没有密码,!表示密码被锁定了,*有密码第三个字段:1970年1......
  • CF836F 做题笔记
    传送门非常好题目,使我原地旋转。首先数据这么小显然直接暴力求出每个\(A_i\)的取值范围。由于每个\(A_i\)只能有一个取值,所以源点先给所有\(A_i\)连一个限流为\(1\),费用为\(0\)的边。同时显然还要给每个值域点(不是\(A_i\))向汇点连限为\(inf\),费用为\(0\)的边......
  • java中的break与continue
    breakbreak:打破结束终止注意事项:1、break不能单独使用,毫无意义2、要在switch语句或者循环语句中使用packagecom.shujia.day03;publicclassBreakDemo{publicstaticvoidmain(String[]args){//需求:循环输出1-5当i为3的时候,使用break......
  • 旅游景点 Tourist Attractions (壮压 DP)题解
    简化题意题目链接——不卡内存班题目链接——卡内存版给定\(n\)个点和\(m\)条边组成的无向图,按照一定限制要求停留\(2\simk+1\)共\(k\)个点(可以经过但不停留),求最短的从\(1\)出发到\(n\)的路径长。限制情况如下:共有\(q\)个限制,接下来\(q\)行,每行两个数\(x......
  • Codeforces 264E Roadside Trees
    首先考虑时间增长的问题,设第\(i\)棵树的种植时间为\(t_i\)。那么第\(x\)棵树比第\(y\)棵树高就是\(h_x+(t_y-t_x)>h_y\),也就是\(h_x-t_x>h_y-t_y\)。所以可以直接用\(h_i-t_i\)当作第\(i\)棵树的高度,即\(h'_i\leftarrowh_i-t_i\)。对于增加,考虑......
  • CodeForces 1844H Multiple of Three Cycles
    洛谷传送门CF传送门首先环是不用管的,只用判环长是否为\(3\)的倍数即可。考虑设\(f(x,y,z)\)表示\(x\)个\(1\)链,\(y\)个\(2\)链,\(z\)个\(0\)链,组成所有环长都为\(3\)的倍数的方案数。注意到\(f(x,y,z)=(x+y+z)f(x,y,z-1)\)(可以接到剩下的任意......