Unity Xlua 之 Lua调用C#(二)

Unity Xlua 之 Lua调用C#(二)

一.Lua使用C#拓展方法

使用C#中的拓展方法,需要在拓展方法那个静态类上面打上标签,Lua才能调用

  • 建议Lua调用C#的类都加上LuaCallCSharp标签,对于程序集中的类,之后的文章有说明
[LuaCallCSharp]
public static class Lesson4Ext
{
    public static void Eat(this Lesson4 lesson4, string str)
    {
        Debug.Log("吃饭: " + str);
    }
}
public class Lesson4
{
    public void Speak(string str)
    {
        Debug.Log("说话: " + str);
    }
}
Lesson4 = CS.Lesson4
local l1 = Lesson4()
l1:Speak("Hello")
--拓展方法
l1:Eat("面包")

二.Lua使用C# ref,out参数的函数

  • 返回值第一个为函数的返回值,其余依次为形参的返回值
  • ref参数需要填写数值
  • out参数不需要填写数值,直接会跳过
public class Lesson5
{
    public int RefFunc(int a, ref int b, ref int c, int d)
    {
        Debug.Log(b);
        Debug.Log(c);
        b = a + d;
        c = a - d;
        return 100;
    }

    public int OutFunc(int a, out int b, out int c, int d)
    {
        b = a + d;
        c = a - d;
        return 1000;
    }

    public int RefOrOutFunc(int a, ref int b, out int c, int d)
    {
        b = a * 100;
        c = d * 200;
        return b + c;
    }
}
Lesson5 = CS.Lesson5
local l5 = Lesson5()
--ref参数需要填写数值
local a,b,c = l5:RefFunc(1,100,100,1)
print(a)
print(b)
print(c)
print("---------------")
--out参数不需要填写数值,直接会跳过
local a,b,c = l5:OutFunc(1,1)
print(a)
print(b)
print(c)
print("---------------")
--结合ref和out
local a,b,c = l5:RefOrOutFunc(1,1,1)
print(a)
print(b)
print(c)

三.Lua使用C#重载函数

  • Lua本身不支持函数重载,但是可以调用C#的重载函数
  • 对于模糊不清的重载函数,Lua无法辨别
  • 可以使用反射强行获取,但是不建议使用
public class Lesson6
{
    public int Calc()
    {
        return 100;
    }

    public int Calc(int a,int b)
    {
        return a + b;
    }

    public int Calc(int a)
    {
        return a;
    }

    public float Calc(float a)
    {
        return a;
    }
}
Lesson6 = CS.Lesson6
local l6 = Lesson6()
print(l6:Calc())
print(l6:Calc(1,1))

print("==============")
print(l6:Calc(10))
print(l6:Calc(10.2))
--Lua本身不支持函数重载,但是可以调用C#的重载函数
--对于模糊不清的重载函数,Lua无法辨别
--可以使用反射强行获取,但是不建议使用
print("==============")
local m1 = typeof(Lesson6):GetMethod("Calc",{typeof(CS.System.Int32)})
local m2 = typeof(Lesson6):GetMethod("Calc",{typeof(CS.System.Single)})
local f1 = xlua.tofunction(m1)
local f2 = xlua.tofunction(m2)
print(f1(l6,10))
print(f2(l6,10.2))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值