Runtime error

Hi, I downloaded Christian Peeters Space Shooter game.

It started out okay then the error message started appearing, but not at the same intervals sometimes I can get up to 12 hits sometimes less.

Did you want me to enter the code?


Guessing from the message, it looks like part of the code is trying to operate/modify on an object that is no longer valid.

If an object can be deleted, and if you have a timer or a listener that modifies the object, you need to add code to either:

  • cancel the timer and or listener BEFORE deleting the object.
  • better/safer - Check the object is valid before you try to modify it.

A basic ‘is valid checker’ looks like this:

local function isValid ( obj )
	return ( obj and obj.removeSelf and type(obj.removeSelf) == "function" )

You can use it like this:

local function rotationAmmo()
   if( isValid(ammo) ) then
       ammo.rotation = ammo.rotation + 45

Hi, Roaminggamer

Can you please explain this isValid function?
I don’t understand why is obj.removeSelf returned from the check?


You’ve read that wrong. It is returning the result of a conditional check, it isn’t returning the elements in the condition. e.g. It is not returning obj.removeSelf, instead it is checking if obj.removeSelf exists.

Let me break it down
return ( obj and obj.removeSelf and type(obj.removeSelf) == "function" )
left to right.

  • return false if obj is nil
  • return false if obj.removeSelf (handle to function) does not exists (is nil)
  • return false if obj.removeSelf handle is present, but does not reference a function.

The obj is nil case should be pretty clear, but what about the other two?

When you delete a display object, the object handle obj is cleaned up. In that cleaning, all references to functions are removed. Thus, the second check above.

The last check is a bit over-the-top, but protects you from the weird case where obj exists and it has a field named removeSelf, but removeSelf is not a function. i.e. This is not a display object.

Ok, get it now.Thank you.