在toLua中,c#得到lua中的表,都只有一个套路,那就是通过luatable来获取
1、在lua中创建List和Dictionary
--table表现的list
testList = {1,2,3,4,5,6}
--table表现的dictionary
testDic = {
["1"] = 1,
["2"] = 10,
["3"] = 20,
["4"] = 30
}
testDic2 = {
["1"] = 1,
[true] = 1,
[false] = true,
["123"] = false
2、在c#中获取lua中table表现的List
LuaTable table = LuaMgr.GetInstance().LuaState.GetTable("testList");
Debug.Log(table[1]);
Debug.Log(table[2]);
Debug.Log(table[3]);
Debug.Log(table[4]);
Debug.Log(table[5]);
通过打印信息可知luaTable的引用也是从1开始的,如果要遍历,需要先将luaTable转为Array数组
object[] objs = table.ToArray();
for (int i = 0; i < objs.Length; i++)
{
Debug.Log("遍历"+objs[i]);
}
luaTable获取的List是引用拷贝,所以如果要修改其中的元素,直接修改即可
table[1] = 999;
3、获取table表现的Dictionary
方法和List相同
LuaTable dic = LuaMgr.GetInstance().LuaState.GetTable("testDic");
Debug.Log(dic["1"]);
Debug.Log(dic["2"]);
Debug.Log(dic["3"]);
Debug.Log(dic["4"]);
这里需要注意一点:通过中括号得到值,只支持int和string,其他类型没办法直接获取。
所以像dic2中的键值没办法直接通过中括号获取,这时需要将luaTable转为LuaDictTable格式,泛型里面分别是键和值的类型。
LuaTable dic2 = LuaMgr.GetInstance().LuaState.GetTable("testDic2");
LuaDictTable<object,object> luaDic = dic2.ToDictTable<object,object>();
Debug.Log(luaDic[true]);
Debug.Log(luaDic[false]);
Debug.Log(luaDic["123"]);
字典遍历建议使用迭代器遍历
IEnumerator<LuaDictEntry<object, object>> ie = luaDic.GetEnumerator();
while (ie.MoveNext())
{
Debug.Log(ie.Current.Key+"_"+ie.Current.Value);
}
同List,字典也是引用拷贝,直接修改即可
dic["1"]=9999;
LuaTable dicTmp = LuaMgr.GetInstance().LuaState.GetTable("testDic");
Debug.Log(dic["1"]);
4、总结:LuaTable中获取出来的都是引用拷贝,在c#中修改其中的元素,lua中对应元素也会修改。