Dynamically creating new display.newImage() objects

I'm trying to get my script to create new image objects in a function, but they need different names, so what I've done is created an id variable that increases every time the function is used, then it add's the id to the string "Block", therefore making the first block "Block1", then "Block2", etc. This is stored in a variable called newBlock. But when I go
newBlock = display.newImage("image.png")

It'll literally make "newBlock" the object instead of "Block1" or whatever. This would be easy in PHP to fix because when you refer to a variable you have to use a "$" prefix, which let's the script know it's actually talking about a variable, not a literal piece of text.

Is there any way to let Lua know I'm talking about a dynamically changing variable here, not a literal piece of text? Or even a better way of doing what I'm trying to do?

Any would be really appreciated!

use an array

1
2
3
4
5
6
7
8
9
10
11
blocks={}
 
for i=1,5,1 do
  local newBlock = display.newImage("image.png")
  newBlock.name = ("block"..i)
  newBlock.id = i
  -- add block to end of array
  blocks[#blocks+1] = newBlock
end
 
print(blocks[3].id .. " : " .. blocks[3].name) -- "3 : block3"

Thanks! Works like a charm!

this is another way.. essentially the same thing though, but note you could move the createBlock function into a different file etc if you wanted

1
2
3
4
5
6
7
8
9
10
11
12
13
14
blocks={}
 
local function createBlock(blockID)
  local newBlock = display.newImage("image.png")
  newBlock.name = ("block"..blockID)
  newBlock.id = blockID
  return(newBlock)
end
 
for i=1,5,1 do
  blocks[i] = createBlock(i)
end
 
print(blocks[3].id .. " : " .. blocks[3].name) -- "3 : block3"
views:1404 update:2011/10/6 9:28:12
corona forums © 2003-2011