toLua学习笔记七——访问lua中table表现的List和Dictionary

17 篇文章 4 订阅

在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中对应元素也会修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值