testFun = function()
print("无参无返回函数")
end
testFun2 = function(a)
print("有参有返回函数,参数a=" .. a)
return a * 2
end
testFun3 = function(a,b)
print("有参多返回函数,参数a=" .. a .. ",参数b=" .. b);
return a + b, a - b,a * b , a + b - a * b ,false,"你好",2
end
testFun4 = function(a,...)
print("变长参数函数,第一个参数a=" .. a .. ",后面是变长参数")
local args = {...}
for i, v in ipairs(args) do
print("参数" .. i .. "=" .. v)
end
return 1, 2, 3, 4, 5
end

使用委托来接受lua函数返回值时,需要添加[CSharpCallLua]特性,并通过XLua/Generate Code生成对应的代码。
using System;
using UnityEngine;
using UnityEngine.Events;
using XLua;
//无参无返回值的委托
public delegate void CustomCall();
//有参有返回值的委托需要加下面的特性,并在编辑器里点击xlue/generate code
[CSharpCallLua]
public delegate int CustomCall2(int a);
//多返回值的委托
[CSharpCallLua]
public delegate int CustomCall3(int a,int b,out int r2,out int r3,out int r4,out bool r5,out string r6,out int r7);
[CSharpCallLua]
public delegate int CustomCall4(int a,int b,ref int r2,ref int r3,ref int r4,ref bool r5,ref string r6,ref int r7);
//变长参数的委托
[CSharpCallLua]
public delegate void CustomCall5(int a,params string[] args);
public class Lesson5_CallFunction : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().DoLuaFile("Main");
var global = LuaMgr.GetInstance().Global;
//以下四种都可获取lua中的无参无返回值方法
//无参无返回的获取
CustomCall call = global.Get<CustomCall>("testFun");
call();
//Untiy自带的委托
UnityAction ua = global.Get<UnityAction>("testFun");
ua();
//C#自带的委托
Action action = global.Get<Action>("testFun");
action();
//XLua提供的委托
LuaFunction luaFunc = global.Get<LuaFunction>("testFun");
luaFunc.Call();
//有参有返回
CustomCall2 customCall2 = global.Get<CustomCall2>("testFun2");
Debug.Log("有参有返回"+customCall2(10));
//C#自带的委托
Func<int,int> func3 = global.Get<Func<int,int>>("testFun2");
Debug.Log("有参有返回"+func3(10));
//XLua自带的委托,返回值是object[]
LuaFunction func4 = global.Get<LuaFunction>("testFun2");
Debug.Log("有参有返回"+func4.Call(25)[0]);
//多返回值
//使用out和ref来接收
CustomCall3 customCall3 = global.Get<CustomCall3>("testFun3");
int r1,r2,r3,r4,r7;
bool r5;
string r6;
//第一个返回值就是委托的返回值!
r1 = customCall3(10,20,out r2,out r3,out r4,out r5,out r6,out r7);
Debug.Log("out接收多返回值"+r1+" "+r2+" "+r3+" "+r4+" "+r5+" "+r6+" "+r7);
//ref传入的变量需要在外部先初始化
CustomCall4 customCall4 = global.Get<CustomCall4>("testFun3");
r1 = customCall4(10,20,ref r2,ref r3,ref r4,ref r5,ref r6,ref r7);
Debug.Log("ref接收多返回值"+r1+" "+r2+" "+r3+" "+r4+" "+r5+" "+r6+" "+r7);
LuaFunction func5 = global.Get<LuaFunction>("testFun3");
//XLua自带的接收,返回值是object[]
object[] ret = func5.Call(10,20);
Debug.Log("LuaFunction接收多返回值"+ret[0]+" "+ret[1]+" "+ret[2]+" "+ret[3]+" "+ret[4]+" "+ret[5]+" "+ret[6]);
//变长参数的委托
CustomCall5 customCall5 = global.Get<CustomCall5>("testFun4");
customCall5(10,"a","b","c");
LuaFunction func6 = global.Get<LuaFunction>("testFun4");
func6.Call(10,"a","b","c");
}
}
评论(0)
暂无评论