Newbie question about conditions

Good morning,

As a beginner in Lua, some of my conditions causes a crash but it shouldn’t be.

Example :

1      if (scene.myVar ~= nil) then

2               scene.myVar:removeSelf()

3      end

Then sometimes,

Runtime Error -> scene:lua:2: attempt to call method ‘removeSelf’ (a nil value)

How could it be ? Might am I wrong ? 

Thank you very much

Remi

First off, when posting code please use the <> button in the text editor - it numbers lines and makes your code presentable.

To your problem - when you get the “a nil value” Corona (or rather, Lua) is telling you that the thing you’re trying to use is nil, not there. In this case, because it looks like you’re trying to call removeSelf() that would imply a display object or group. Therefore, the .myVar variable is not nil but it is also not a display object or group.

What you could do, for debugging, is put an extra if statement inside this one, like this:

if (scene.myVar ~= nil) then if (scene.myVar.removeSelf == nil) then print("myVar is not a display object") else scene.myVar:removeSelf() end end

Well, I will try it.

Indeed, I didn’t know that we could test on “removeSelf field”.

Thank you very much !

First off, when posting code please use the <> button in the text editor - it numbers lines and makes your code presentable.

To your problem - when you get the “a nil value” Corona (or rather, Lua) is telling you that the thing you’re trying to use is nil, not there. In this case, because it looks like you’re trying to call removeSelf() that would imply a display object or group. Therefore, the .myVar variable is not nil but it is also not a display object or group.

What you could do, for debugging, is put an extra if statement inside this one, like this:

if (scene.myVar ~= nil) then if (scene.myVar.removeSelf == nil) then print("myVar is not a display object") else scene.myVar:removeSelf() end end

Well, I will try it.

Indeed, I didn’t know that we could test on “removeSelf field”.

Thank you very much !