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))