如何使用Lua脚本迭代嵌套的Lua表
我使用Lua脚本来解析这个结构中Lua文件中的数据。由于嵌套的方式,我很难提取所有“group=”值。我尝试了以下print命令的许多变体,甚至可以只获得一个值,但似乎找不到正确的语法。我需要能够遍历所有group=“items”并打印出来 打印(itemGroups.groups[1][2]) 打印(itemGroups.groups.group[1])如何使用Lua脚本迭代嵌套的Lua表,lua,Lua,我使用Lua脚本来解析这个结构中Lua文件中的数据。由于嵌套的方式,我很难提取所有“group=”值。我尝试了以下print命令的许多变体,甚至可以只获得一个值,但似乎找不到正确的语法。我需要能够遍历所有group=“items”并打印出来 打印(itemGroups.groups[1][2]) 打印(itemGroups.groups.group[1]) 您可能希望使用以下选项: local firstGroup = itemGroups[1] local itemChance = first
您可能希望使用以下选项:
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中使用表作为{key=value}
时,可以使用table.key
获取值。如果使用数组,如在{value1,value2}
中,可以使用表[1]
获取第一个值,使用表[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
您可能希望使用以下选项:
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中使用表作为{key=value}
时,可以使用table.key
获取值。如果使用数组,如在{value1,value2}
中,可以使用表[1]
获取第一个值,使用表[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
如果答案对您的问题有帮助,请使用复选标记按钮接受它!它帮助未来的读者解决类似的问题!如果答案对您的问题有帮助,请使用复选标记按钮接受它!它帮助未来的读者解决类似的问题!工作完美!!谢谢你的及时回复。很抱歉,我花了这么长时间才回到这个测试。工作得很好!!谢谢你的及时回复。抱歉,我花了这么长时间才回到这个测试。