0

Basically, I need to create layers from five images. Is there a way to do this with a for loop, as opposed to manually creating the layers? The following code was my attempt, but I'm not sure how to debug from here.

tabs_strings = ["nearby", "adopted", "my_cats", "settings", "bruce"]

for tab in [0..tabs_strings]
    tab = new Layer 
        x:0, y:0, width:640, height:1136, image:"images/#{tab}.jpg" 

# nearby = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/nearby.jpg"
# adopted = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/adopted.jpg", opacity: 0
# my_cats = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/my_cats.jpg", opacity: 0
# settings = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/settings.jpg", opacity: 0
# bruce = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/bruce.jpg", opacity: 0
nipponese
  • 2,813
  • 6
  • 35
  • 51

2 Answers2

1

Is your question that the code you posted does not work and that you are looking for an alternative solution?

EDIT:

The only problem I see here is that you are using "tab" for both the string variable passed from the current position in the array, as well the new Layer object that you are initializing.

Try this:

tabs_strings = ["nearby", "adopted", "my_cats", "settings", "bruce"]

for tab in [0..tabs_strings.length]
    tabLayer = new Layer 
          x:0, y:0, width:640, height:1136, image:"images/#{tab}.jpg"
  • It seems like the problem is that the layer objects are not created... for example, if I modify the properties to `tabLayer = new Layer x:0, y:0, width:640, height:1136, backgroundColor = "#FFF", opacity: 1` I don't see any white 640x1136 rects. – nipponese Sep 04 '14 at 05:15
  • The double use of `tab` inside the loop is fine (confusing perhaps but not a problem). The `for`-loop OTOH... – mu is too short Sep 04 '14 at 05:18
1

Your for loop is, um, strange. tabs_strings is itself an array so you're saying:

for i in [0 .. some_array]

rather than the usual:

for i in [0 .. some_number]

or

for e in some_array

If you look at the JavaScript version, you'll see this:

for (tab = _i = 0; 0 <= tabs_strings ? _i <= tabs_strings : _i >= tabs_strings; tab = 0 <= tabs_strings ? ++_i : --_i) {

so you end up comparing 0 with an array and that's not terribly productive.

I think you want to use the for e in array form of the for-loop:

for tab in tab_strings
    new Layer 
        x:0, y:0, width:640, height:1136, image:"images/#{tab}.jpg" 

There's no need for the tab assignment inside the loop so I took that out.

mu is too short
  • 426,620
  • 70
  • 833
  • 800