Reputation: 37
I am using a Lua script to parse data from a Lua file in this structure. I'm having difficulty pulling all of "group = " values because of the way it's nested. I've tried many variations of the following print command to be able to even get just one value but cannot seem to find the correct syntax. I need to be able to loop through all group = "items" and print them out.
print(itemGroups.groups[1][2])
print(itemGroups.groups.group[1])
itemGroups = {
{
groups = {
{group = "item1", chance = 10},
{group = "item2", chance = 20},
{group = "item3", chance = 30},
},
itemChance = 50
}
}
Upvotes: 0
Views: 1434
Reputation: 755
You probably want to use this:
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
When you use a table in Lua as {key=value}
, you can get the value by using table.key
. If you use an array, as in {value1,value2}
, you can get the first value using table[1]
and the second value using table[2]
.
If you want to loop over all groups and print their name and chance:
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
Output:
Groups in itemgroup #1:
item1: 10
item2: 20
item3: 30
Upvotes: 2