pcall(object:removeSelf()) works only in main.lua

I just noticed a strange behavior of pcall function. I often create display objects and then remove them. Due to delays I have to do a nil check and in 99% of cases it works wonderfully:

if object ~= nil then
  object:removeSelf()
end

But sometimes, especially on physical devices, removeSelf() gives an error that the object is still nil! So, I decided to use remove-lines in a pcall-wrap… Guess what:

pcall(object:removeSelf()) works only in main.lua, but if it is situated in any of the scenes, then it gives an error. Check it for yourself. I guess it is a bug.

I’ve reopened the post, as per your request.

You’ll need to provide more code (or even a downloadable project) to demonstrate this issue. I’ve used loadstring, pcall and xpcall quite extensively and I haven’t experienced any such issues.

Also, you might want to consider using display.remove(object) as it will first check if the object exists before trying to remove it.

1 Like

Oh, and is object a local or a global variable in your example? The aforementioned functions only work in global scope, so if your variable is local, they won’t be able to access it.

Tip: Ignoring the ‘pcall’ aspets of this. Never use object:removeSelf(). Use display.remove( object ) instead. It is safer.

1 Like

breaks down roughtly to

local result = object:removeSelf()

pcall(result)

So it’s attempting the remove, then pcall()-ing the result if it gets that far.

As the name implies, pcall() calls something, so you want to supply it a function:

pcall(function()
  object:removeSelf()
end)

Now I peppered my code with display.remove(object)'s lines. It might solve the issue.

You can check it like this:

if object ~= nil and object.removeSelf ~= nil then
  object:removeSelf()
end
object = nil

this solution is fast and stable