0

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
 }
}
warspyking
3,1435 gold badges22 silver badges38 bronze badges
asked Feb 22, 2016 at 12:35
1
  • If the answer helped you with your problem please accept it using the checkmark button! It helps future readers with the similar problems! Commented Feb 23, 2016 at 21:28

1 Answer 1

2

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
answered Feb 22, 2016 at 13:09
1
  • Worked perfect!! Thank you for the prompt response. Sorry it took me so long to get back to this to test. Commented Feb 27, 2016 at 19:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.