attempt to index upvalue 'element' (a nil value)

What means?

The code is:

--local variable to create new elements
local elements

--function to create new obstacles and animals
local function createElement( event )
   -- 1, 3, 6, 8 = obstacles
   -- 2, 4, 5, 7 = animals

   -- Depending on the number, the uploaded image changes
   local rType = math.random(1, 8)

   -- obstacles 
   if(rType == 1 or rType == 6) then
      element = display.newImageRect(sceneGroup,"img/flame.png", 70, 70);
      element.myName = "flame"
      element.x = 1080
      element.y = display.contentHeight-150
      physics.addBody(element, "dynamic", {density=1.3, friction=1.0 })
      
   -- obstacles 2
   elseif(rType == 3 or rType == 8) then
      element = display.newImageRect(sceneGroup,"img/petrolio.png", 90, 90);
      element.myName = "petrolio"
      element.x = 1080
      element.y = display.contentHeight-100      
      physics.addBody(element, "dynamic", { bounce = 0.0, density=1.3, friction=1.0 })
      
   --animals
   elseif (rType == 2 or rType == 5) then      
      element= display.newImageRect(sceneGroup,"img/rabbit.png", 80, 80);
      element.myName = "rabbit"
      element.x = 1080 
      element.y = display.contentHeight-200      
      physics.addBody(element, "dynamic", {bounce = 0.0, density=1.3, friction=1.0})
   end
      
   table.insert(elements, element)
   return element
end 

--function that implements the horizontal scrolling of each active obstacle
local function obstacleScroll(self, event)
   self.x = self.x - elementSpeed
end

--
function to manage the video game loop
local function gameLoop()
   -- creazione nuovo ostacolo fuori dal display
   element=createElement()
   -- activation of the horizontal scrolling of obstacles to make them enter the display
    element.enterFrame = obstacleScroll
    Runtime:addEventListener("enterFrame",element)
   
   for i,thisElement in ipairs(elements) do
      if thisElement.x < -display.contentWidth then
         Runtime:removeEventListener("enterFrame",thisElement)
         display.remove(thisElement)
         table.remove(elements,i)
      end
   end      
end

gameLoopTimer = timer.performWithDelay(1000,gameLoop,0)

(Post edited by moderator; Please format code in posts using triple-back ticks to enclose code.; Click pencil icon to review changes and see how coed was reformatted.)

Who can help me?
thanks!

@s1507

  1. I re-formatted your code (please edit your post to see what I did to make it legible.)

  2. It seems that your function createElement() is getting a random value of 7 for rType, but you don’t have a case for that so the function returns nil.

  3. That nil is then being operated on in gameLoop() and of course fails.

Update your createElement() function to handle all possible random values. i.e. Add an else case to handle the rest.

1 Like