nested pair iterations

Hi guys,

What is the correct way to iterate through a nested table like this one

game\_data ={  
 collection1 = {  
 physicsGameItems ={  
 {name= "candy1", width=35,height= 35},  
 {name= "candy2", width=45,height= 35},  
 }  
 },  
 collection2 ={  
 physicsGameItems ={  
 {name= "candy1",width=35,height= 35 },  
 }  
 }  
}  

The output I want to get from this table, is the contents of physicsGameItems from collection1.
so far I have this, but as you can see I can’t figure out how to iterate inside collection1

for k,v in pairs(physicsCandyItems) do  
 if k == "collection1"then  
  
 --Im stuck here  
 end  
 end  
  

thanks a lot for your help [import]uid: 74667 topic_id: 31360 reply_id: 331360[/import]

Hi @potsifera ,
You don’t need to use a “pairs” iteration if you are labeling (naming) your sub-tables by names that will remain constant and that you can look up. Just “drill down” to the table you need and then loop by count (index number). Like this…

local t = game\_data["collection1"]["physicsGameItems"]  
  
for i=1,#t do  
 local ind = t[i]  
 print( ind.name )  
 print( ind.width )  
 print( ind.height )  
end  

Hope this helps!
Brent
[import]uid: 9747 topic_id: 31360 reply_id: 125388[/import]

Or even better, rely on Lua’s iterators, and generate less locals.

local item\_list = game\_data.collection1.physicsGameItems for i,item in ipairs(item\_list) do print(item.name) print(item.width) print(item.height) end [import]uid: 142361 topic_id: 31360 reply_id: 125431[/import]

thanks @Brent Sorrentino and @roland.yonaba!! your tips helped me a lot to get this loop done just right :slight_smile:
cheers! [import]uid: 74667 topic_id: 31360 reply_id: 125671[/import]

Hi @potsifera ,
You don’t need to use a “pairs” iteration if you are labeling (naming) your sub-tables by names that will remain constant and that you can look up. Just “drill down” to the table you need and then loop by count (index number). Like this…

local t = game\_data["collection1"]["physicsGameItems"]  
  
for i=1,#t do  
 local ind = t[i]  
 print( ind.name )  
 print( ind.width )  
 print( ind.height )  
end  

Hope this helps!
Brent
[import]uid: 9747 topic_id: 31360 reply_id: 125388[/import]

Or even better, rely on Lua’s iterators, and generate less locals.

local item\_list = game\_data.collection1.physicsGameItems for i,item in ipairs(item\_list) do print(item.name) print(item.width) print(item.height) end [import]uid: 142361 topic_id: 31360 reply_id: 125431[/import]

thanks @Brent Sorrentino and @roland.yonaba!! your tips helped me a lot to get this loop done just right :slight_smile:
cheers! [import]uid: 74667 topic_id: 31360 reply_id: 125671[/import]