如何使用LUA脚本遍历嵌套的Lua表

史考特

我正在使用Lua脚本来解析此结构中Lua文件中的数据。由于嵌套的方式,我很难提取所有“ group =”值。我尝试了以下print命令的多种变体,使其甚至只能获得一个值,但似乎找不到正确的语法。我需要能够遍历所有组=“项目”并打印出来。

打印(itemGroups.groups [1] [2])

打印(itemGroups.groups.group [1])

itemGroups = {
        {
        groups = {
            {group = "item1", chance = 10},
            {group = "item2", chance = 20},
            {group = "item3", chance = 30},
        },
        itemChance = 50
        }
}
爱因斯坦K.

您可能要使用此:

local firstGroup = itemGroups[1]
local itemChance = firstGroup.itemChance -- 50
local group = firstGroup.groups[1] -- first group
local name = group.group -- "item1"
local chance = group.chance -- 10
-- If you want to use it all in one line:
name = itemGroups.groups[1].group -- "item1"
chance = itemGroups.groups[1].chance-- 10

在Lua中以as形式使用表时{key=value},可以使用来获得值table.key如果使用数组(如中){value1,value2},则可以使用来获取第一个值,table[1]使用来获取第二个值table[2]

如果要遍历所有组并打印其名称和机会,请执行以下操作:

for index,itemgroup in pairs(itemGroups) do
    print("Groups in itemgroup #"..index..":")
    for k,v in pairs(itemgroup.groups) do
        print("\t"..v.group..": "..v.chance)
    end
end

输出:

Groups in itemgroup #1:
    item1: 10
    item2: 20
    item3: 30

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章