contentBounds is nil error after changing composer scenes AND trying to restart level

I have an object which I pass to a function in another module to determine boundaries of enemy movement.  

I get these bounds via some code like this in the other module:

local bounds = enemy\_box.contentBounds local xMin = bounds.xMin local xMax = bounds.xMax local yMin = bounds.yMin local yMax = bounds.yMax

The main code that calls this function is in a composer scene. 

Everything worked fine UNTIL:

  1.  I added code to restart the current level  

  2.  I added code to switch to another scene and back again

When both of these things come into play, I start to see a problem.

Here is what happens:   

-If I play the level once, everything works fine.

-If I restart the level multiple times but do NOT change the scene, everything works fine.

-If I change scene back and forth but do NOT restart the level, everything works fine.

-ONLY IF I change scenes AND THEN try to restart the level do I get "attempt to index local ‘bounds’ (a nil value)

It comes from the line of code that tries to call the function to get the bounds of the enemy box.

So without posting hundreds of lines of code… is there something I can try to figure out what is going on? 

The object itself that I am passing to the function is not nil, it seems that only the contentBounds table is nil. 

But what I do not understand is why does this only happen in the one situation mentioned above?  

Is there something regarding contentBounds and switching composer scenes that I need to be aware of?

When I switch scenes I am composer.removeScene  on the level scene to make sure things get recreated properly when I go back to the scene.  Like I said, this works fine as long as I don’t try to restart the level after changing scenes. 

You really need to share some code if you want people to make anything other than educated guesses.

If you create a local variable and then move to a different scene, then that variable will be outside of the other scene’s scope. When you restart a level, the local variable may fall out of scope as well. How does this happen and why? I don’t know, I’m just guessing without seeing any of your code.

I thought about that but I’ve got several hundred lines of code across multiple modules… Do I just post it all? I would narrow it down to the problem area but I don’t know where that is. Guess I was just wondering if anyone else had experienced any issues with nil contentBounds when changing scenes.

The issue is almost definitely about scope. It’s just time for you to start debugging.

See “Scope for Beginners” tutorial: https://docs.coronalabs.com/tutorial/basics/scope/index.html

Yes I understand scope. I will see if I can sift through and post the relevant code so you have something more to go on. I spent several hours debugging but cannot find why contentBounds is nil only in one weird case but not nil in every other similar case.