In my game, I am pulling two of the same item from a matchimgs{} table and placing them into separate objects (item1 and item2) in order to display one of each on opposite sides of the screen. The reason I created two separate ones is because item1 affects Player1’s score; item2 affects Player2’s score.
My problem is that for whatever reason, item1 sometimes becomes nil, even though I am just telling it to pull any one of the 12 items from my matchimgs{} table. Sometimes I have no problems many times in a row, other times it gets to the line saying “item1:scale(.5, .5)” and throws this exception:
Attempt to index upvalue ‘item1’ (a nil value)
local matchimgs = { "images/items/beachball.png", "images/items/bread.png", "images/items/carrot.png", "images/items/cheese.png", "images/items/diamond.png", "images/items/eggs.png", "images/items/flower\_red.png", "images/items/lettuce.png", "images/items/pineapple.png", "images/items/star.png", "images/items/sunglasses.png", "images/items/watermelon.png" };
if gameIsActive == true then -- Add matching pair to the screen randomMatchImage = matchimgs[math.random(#matchimgs)] --pick one item from matchimgs table above math.randomseed(os.time()) local function getItem1() if randomMatchImage == nil then randomMatchImage = matchimgs[math.random(#matchimgs)] --pick one item from matchimgs table above end file1 = randomMatchImage item1 = display.newImage(file1) item1:scale(.5, .5) item1.x = math.random(100, centerX - 50) item1.y = math.random(75, display.contentHeight - 180) item1.name = "item1" item1:rotate(math.random(-45,315)) item1.postCollision = onOverlap item1:addEventListener("tap", buttonListener) physics.addBody(item1, "static", {radius = 80, density = 1.0, friction = 50, bounce = 100, isSensor = false}) group:insert(item1) end local function getItem2() file2 = file1 --make a copy of file1 item2 = display.newImage(file2) item2:scale(.5, .5) item2.x = math.random(centerX + 50, display.contentWidth - 100) item2.y = math.random(75, display.contentHeight - 180) item2.name = "item2" item2:rotate(math.random(-270,270)) item2.postCollision = onOverlap item2:addEventListener("tap", buttonListener) physics.addBody(item2, "static", {radius = 80, density = 1.0, friction = 50, bounce = 100, isSensor = false}) group:insert(item2) end getItem1()
Any clue why?