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
}
}
-
If the answer helped you with your problem please accept it using the checkmark button! It helps future readers with the similar problems!warspyking– warspyking2016年02月23日 21:28:20 +00:00Commented Feb 23, 2016 at 21:28
1 Answer 1
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
-
Worked perfect!! Thank you for the prompt response. Sorry it took me so long to get back to this to test.ScottEH– ScottEH2016年02月27日 19:20:28 +00:00Commented Feb 27, 2016 at 19:20