Objects spawn with incorrect values

The below function triggers every second spawning more objects, it was working fine but since adding code elsewhere (that does not applie to this function) the data values do not match up with the spawn image - unless I change the spawn time to a much longer interval.

As far as I can tell this function is taking longer than a second to complete so before the values get assigned to the randomly spawned item the item number has increased from the next instance of the function so the wrong data gets referenced.

I have tried putting the numItem +1 at the end of the function to prevent that but it crashes at the onCollison event due to nil values occuring. Having long spawn times would not be suitable, I am sure there is a work around but I can’t think of another alternative so any help would be appreciated.

   function spawnItem()         if (pausegame == true) then         return true             else             numItem = numItem + 1             print(numItem)             math.randomseed(os.time())             math.random(); math.random()                              local  selectItem = math.random(1, #itemdata)                              itemgroup:toFront()                itemArray[numitem] = display.newImageRect(itemdata[selectItem].img, 40, 40)                 physics.addBody (itemArray[numItem], {density=0.5, friction=0, bounce=0})                                  itemArray[numItem].myName = itemdata[selectItem].name                 itemArray[numItem].istype = itemdata[selectItem].istype                itemArray[numItem].value = itemdata[selectItem].value                 itemArray[numItem].score = itemdata[selectItem].score                 startlocationX = display.contentWidth + 50                itemArray[numItem].x = startlocationX                 startlocationY = math.random (0, display.contentHeight)                 itemArray[numItem].y = startlocationY                 itemgroup:insert(itemArray[numItem] )                 sceneGroup:insert(itemgroup) end     end

Nevermind, solved it.

I was being daft and had referred to itemArray[numItem] instead of event.other2 in the collision detection. Simple fix once I saw where I had gone wrong!

Nevermind, solved it.

I was being daft and had referred to itemArray[numItem] instead of event.other2 in the collision detection. Simple fix once I saw where I had gone wrong!