Unity ToLua 之 C#调用Lua(三)
- ToLua和XLua不同,XLua相当于映射,而ToLua相当于访问(ToLua中对表的操作都是引用)
一.访问List和Dictionary
- 设置LuaTable都是按引用设置
testList1 = {10,20,30,40}
testList2 = {false,"zzs",1,6.6}
testDic1 = {
["zzs"] = 1,
["wy"] = 22,
["pnb"] = 333
}
testDic2 = {
[true] = "zzs",
[1] = 88.92,
["wy"] = false
}
public class Lesson06_ListDic : MonoBehaviour
{
private void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().Require("Main");
var luaState = LuaMgr.GetInstance().LuaState;
//List映射
var luaTable1 = luaState.GetTable("testList1");
Debug.Log(luaTable1[1]);
foreach (var item in luaTable1.ToArray())
{
Debug.Log(item);
}
//引用传递
luaTable1[1] = 999;
Debug.Log(luaState.GetTable("testList1")[1]);
Debug.Log("====================");
var luaTable2 = luaState.GetTable("testList2");
Debug.Log(luaTable2[1]);
luaTable2[1] = 888.8;
foreach (var item in luaTable2.ToArray())
{
Debug.Log(item);
}
Debug.Log("======Dic映射======");
//Dic映射
var dic1 = luaState.GetTable("testDic1");
Debug.Log(dic1["zzs"]);
Debug.Log(dic1["wy"]);
Debug.Log(dic1["pnb"]);
var d = dic1.ToDictTable<string, int>();
foreach (var item in d)
{
Debug.Log(item.Key);
Debug.Log(item.Value);
}
var dic2 = luaState.GetTable("testDic2");
var dd = dic2.ToDictTable<object, object>();
//引用传递
dd["wy"] = 3.14;
foreach (var item in dd)
{
Debug.Log(item.Key);
Debug.Log(item.Value);
}
}
}
二.访问类
testClass = {
age = 18,
name = "zzs",
Eat = function ()
print("我吃东西")
end
}
public class Lesson07_Class : MonoBehaviour
{
void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().Require("Main");
var luaState = LuaMgr.GetInstance().LuaState;
var testClass = luaState.GetTable("testClass");
Debug.Log(testClass["age"]);
Debug.Log(testClass["name"]);
var func = testClass.GetLuaFunction("Eat");
func.Call();
}
}
三.使用协程
- 使用协程时需要添加LuaLooper脚本,并初始化才能使用协程
- 注意,下面的Lua代码的协程写法是ToLua为其提供的正常的Lua和XLua不能这么写
local cor = nil
StartDelay = function()
cor = coroutine.start(Delay)
end
Delay = function()
local a = 1
while true do
print(a)
coroutine.wait(1)
a = a + 1
if a > 5 then
StopDelay()
break
end
end
end
StopDelay = function()
coroutine.stop(cor)
end
public class Lesson08_Coroutine : MonoBehaviour
{
private void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().Require("Main");
var luaState = LuaMgr.GetInstance().LuaState;
var func = luaState.GetFunction("StartDelay");
func.Call();
}
}

版权声明:本文为zzzsss123333原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。