Unity Xlua 之 C#调用Lua(二)
一.全局变量的获取
只能获取全局变量通过GlobalTable
public class Lesson04_LuaGlobal : MonoBehaviour
{
private void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().LoadFile("Main");
var globalTable = LuaMgr.GetInstance().Global;
var testInt = globalTable.Get<int>("TestInt");
var testFloat = globalTable.Get<float>("TestFloat");
var testDouble = globalTable.Get<double>("TestFloat");
var testBool = globalTable.Get<bool>("TestBool");
var testString = globalTable.Get<string>("TestString");
Debug.Log(testInt);
Debug.Log(testFloat);
Debug.Log(testDouble);
Debug.Log(testBool);
Debug.Log(testString);
globalTable.Set("TestInt",666);
testInt = globalTable.Get<int>("TestInt");
Debug.Log(testInt);
}
}
二.全局函数的获取
自定义委托时需要打上标签,然后重新生成代码,尽量使用委托,而不是LuaFunction,这样容易产生垃圾消耗
[CSharpCallLua]
public delegate void Custom1();
[CSharpCallLua]
public delegate int Custom2(int a);
[CSharpCallLua]
public delegate void Custom3(string a, out int ra, out string rb, out bool rc, out float rd, out string re);
[CSharpCallLua]
public delegate void Custom4(int a, params int[] arr);
public class Lesson05_LuaFunc : MonoBehaviour
{
private void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().LoadFile("Main");
var globalTable = LuaMgr.GetInstance().Global;
var call1 = globalTable.Get<Custom1>("TestFunc1");
call1?.Invoke();
var ac1 = globalTable.Get<Action>("TestFunc1");
ac1?.Invoke();
var ua1 = globalTable.Get<UnityAction>("TestFunc1");
ua1?.Invoke();
var func1 = globalTable.Get<LuaFunction>("TestFunc1");
func1?.Call();
var call2 = globalTable.Get<Custom2>("TestFunc2");
Debug.Log(call2?.Invoke(1));
var func = globalTable.Get<Func<int, int>>("TestFunc2");
Debug.Log(func?.Invoke(1));
var func2 = globalTable.Get<LuaFunction>("TestFunc2");
Debug.Log(func2.Call(1)[0]);
var call3 = globalTable.Get<Custom3>("TestFunc3");
call3.Invoke("wy", out var ra, out var rb, out var rc, out var rd, out var re);
Debug.Log($"{ra},{rb},{rc},{rd},{re}");
var func3 = globalTable.Get<LuaFunction>("TestFunc3");
var arr = func3.Call("wy");
foreach (var item in arr)
Debug.Log(item);
var call4 = globalTable.Get<Custom4>("TestFunc4");
call4.Invoke(10, 3, 45, 23, 45, 56, 7, 222);
var func4 = globalTable.Get<LuaFunction>("TestFunc4");
func4.Call(10, 3, 45, 23, 45, 56, 7, 222);
}
}
Lua脚本
TestFunc1 = function ()
print("无参无返回")
end
TestFunc2 = function (a)
print("有参有返回")
return a + 1
end
TestFunc3 = function (a)
print("多返回")
return 123,"zzs",true,1.333,a
end
TestFunc4 = function (a,...)
print("变长参数")
local t = {...}
for key, value in pairs(t) do
print(key,value)
end
end
|