How to traverse a table of displayObjects?

I’ve been developing for several months and written lots of code. But the following problem is causing me issues. Up to now I’ve been duplicating code as a work around, but really want to learn how to do it properly!

I have a table to hold my displayObjects in this case a list of buttons eg.

butt = {back,color,forward}

butt.back = display.newImage(file)

each is a displayObject or nil all correctly assigned with all data correct and working properly.

Question: How do I traverse all these buttons? in the current App I have about 10 buttons I want to change the y coord when changing the device orientation, but could just as easily be removing, or shifting all the buttons.

I’ve tried in pairs and ipairs but don’t really understand those structures, the ‘Programming-in-Lua Guide’ jumps through these in a paragraph each, if you don’t get it immediately you’re lost! also

for i=1, #butt do – is wrong I think
for i=1, (butt.numChildren) do --gives an error

Help!
[import]uid: 3093 topic_id: 23798 reply_id: 323798[/import]

You have a several valid options for doing this.

Key/value pairs:

local buttons = {}  
  
buttons.back = display.newImage()  
buttons.forward = display.newImage()  
  
for key,button in pairs(buttons) do  
 print(key, button)  
end  

Index table:

local buttons = {}  
  
buttons[1] = display.newImage(back.png)  
buttons[2] = display.newImage(forward.png)  
  
for i,button in ipairs(buttons) do --Note the distinction between pairs and ipairs  
 print(i, button)  
end  
  
--Alternatively  
for i=1, #buttons do  
 print(i, buttons[i])  
end  

Display group:

local buttons = display.newGroup()  
  
buttons:insert(display.newImage(back.png))  
buttons:insert(display.newImage(forward.png))  
  
for i=buttons.numChildren, 1, -1 do  
 print(i, buttons[i])  
end  

Display groups are nice because you can move the whole group, change the opacity of all objects inside it, and so on.

--Fade in all the buttons from the last snippet  
buttons.alpha = 0  
transition.to(buttons, {time=1000, alpha=1})  

The thing to note is that tables can store key/value pairs (like a dictionary) and indexed values (like an array). So make sure you’re traversing tables the same way you’re storing data in them.

Consult the lua docs for more details, there’s a ton of stuff you can do with tables:
http://lua-users.org/wiki/TablesTutorial [import]uid: 87138 topic_id: 23798 reply_id: 95834[/import]

the clearest and most informative page of documentation I’ve read on this site. Much appreciated!

[import]uid: 3093 topic_id: 23798 reply_id: 95838[/import]