Is there a quicker way to do this?

I have this code, which is pretty long:

local layer1 = display.newGroup();
local layer2 = display.newGroup();
local layer3 = display.newGroup();
local layer4 = display.newGroup();
local layer5 = display.newGroup();
local layer6 = display.newGroup();
local layer7 = display.newGroup();
local layer8 = display.newGroup();
local layer9 = display.newGroup();
local layer10 = display.newGroup();
local layer11 = display.newGroup();
local layer12 = display.newGroup();
local layer13 = display.newGroup();
local layer14 = display.newGroup();
local layer15 = display.newGroup();
local layer16 = display.newGroup();
local layer17 = display.newGroup();
local layer18 = display.newGroup();
local layer19 = display.newGroup();
local layer20 = display.newGroup();
local layer21 = display.newGroup();
local layer22 = display.newGroup();
local layer23 = display.newGroup();

I’d like to do this:

for i=1, 23 do
local layer…i = display.newGroup();
end

But I’m not sure what to put in the layer…i part to dynamically name the group?

Any help much appreciated

Tom [import]uid: 55068 topic_id: 10653 reply_id: 310653[/import]

Aha got it. :slight_smile:

[lua]function create_layers()
for i = 1, 23 do
_G[“layer”…i] = display.newGroup();
end
end

create_layers() [/lua]

… although if anyone could explain what ‘_G’ means I’d appreciate it. I’ve read a lot of explanations but can’t get my head around it? Please imagine you’re explaining it to a child. :slight_smile: [import]uid: 55068 topic_id: 10653 reply_id: 38687[/import]

Hey there,

_G is global as opposed to local - there’s some more info in the API section if you want a technical explanation.

Peach :slight_smile: [import]uid: 52491 topic_id: 10653 reply_id: 38689[/import]

@tomArmstrong

you can use the same, but instead of using the _G you can use our own variable

[lua]local _layers={}

local function createLayers()
local i
for i=1,23 do
_layers[i] = display.newGroup()
end
end

createLayers()[/lua]
now to access a particular layer, all you need to do is

_layers[x] ===> is the layer, where x is the layer number you want

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 10653 reply_id: 38709[/import]

Hi jayantv

Thanks for that.

Can you please explain what the _ part before layers means? I’m used to coding in php and some of this stuff is taking a while to get my head round. :wink:

Thanks

Tom [import]uid: 55068 topic_id: 10653 reply_id: 38719[/import]