attempt to perform arithmetic on field 'x' (a nil value)

the line of code where it gives an error is
–funzione che implementa lo scorrimento orizzontale di ogni ostacolo attivo
local function obstacleScroll(self, event)
self.x=self.x - elementSpeed
end

the code before is
– Funzione per la creazione degli ostacoli e animali
local function createElement( event )

-- 1, 3, 6, 8 = ostacoli  
-- 2, 4, 5, 7 = animali
-- In base al numero cambia l'immagine caricata
local rType = math.random(1, 8)


if(rType == 1 or rType == 6) then
	element = display.newImageRect(sceneGroup,"img/flame.png", 80, 80);
	element.myName = "flame"
	
	-- L'elemento generato viene posizionato in modo casuale, ma entro i margini dello schermo
	element.x = 1080
	element.y = display.contentHeight-150
    -- Aggiungiamo un corpo statico all'asteroide la cui forma sia quella del png in modo da poter gestire le collisioni
	
	physics.addBody(element, "dynamic", {density=1.3, friction=1.0 })

elseif(rType == 3 or rType == 8) then
	element = display.newImageRect(sceneGroup,"img/petrolio.png", 80, 80);
	element.myName = "petrolio"
	
	-- L'elemento generato viene posizionato in modo casuale, ma entro i margini dello schermo
	element.x = 1080
	element.y = display.contentHeight-100
     -- Aggiungiamo un corpo statico all'ostacolo petrolio la cui forma sia quella del png in modo da poter gestire le collisioni
    physics.addBody(element, "dynamic", { bounce = 0.0, density=1.3, friction=1.0 })
	

elseif (rType == 2 or rType == 5) then
	
	element= display.newImageRect(sceneGroup,"img/rabbit.png", 80, 80);
	element.myName = "rabbit"
			
	-- L'elemento generato viene posizionato in modo casuale, ma entro i margini dello schermo
	element.x = 1080 
	element.y = display.contentHeight-200
	
     -- Aggiungiamo un corpo statico all'animale la cui forma sia quella del png in modo da poter gestire le collisioni

    physics.addBody(element, "dynamic", {bounce = 0.0, density=1.3, friction=1.0})

end
	
table.insert(elements, element)
return element
end 

who can help me? thanks!

When you get an error like that it is almost certainly because the display object has been removed, and therefore its x property is nil.

Depending on what your code look like there are some ways to avoid it:

  • Make sure that obstacleScroll() function is not called after the object has been removed.
  • Check that self.x ~= nil before trying to perform arithmetic
  • Set a specific “removed” flag on your object when removing it so you can check that instead of self.x

A side note: You should make it into a habit to write and comment all your code in English. It’s a lot easier when you need someone else to have a look at your code. :slight_smile:

You can also give your objects an “alive”
object.alive = true
That way if they have a death event, like an explosion, you can set
object.alive = false
and stop all interaction with the object (I’m thinking ahead to the next error. . . )