# what's wrong with this Lua code (creating text inside listener in Corona)

If you double/triple click on the myObject here the text does NOT disappear. Why is this not working when there are multiple events being fired?

That is, are there actually multiple "text" objects, with some existing but no longer having a reference to them held by the local "myText" variable? Do I have to manually removeSelf() on the local "myText" field before assigning it another "display.newText(...)"?

display.setStatusBar( display.HiddenStatusBar )

local myText

local function hideMyText(event)
print ("hideMyText")
myText.isVisible = false
end

local function showTextListener(event)
if event.phase == "began" then
print("showTextListener")
myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
timer.performWithDelay(1000, hideMyText, 1 )
end
end

-- Display object to press to show text
local myObject = display.newImage( "inventory_button.png", display.contentWidth/2, display.contentHeight/2)
myObject:addEventListener("touch", showTextListener)


Question 2 - Also why is it the case that if I add a line BEFORE "myText = ..." of: a) "if myText then myText:removeSelf() end" => THIS FIXES THINGS, whereas b) "if myText then myText=nil end" => DOES NOT FIX THINGS

Interested in hearing how Lua works here re the answer...

## 1 Answer

When you call obj:removeSelf(), it removes corona metatable from object and remove it from display hierarchy. But the object is not completely removed after this, it becomes a simple lua table {}. So you must set it to nil, to the garbage collector deleted it completely.

You can change your listener to this:

local function showTextListener(event)
if event.phase == "began" and myText ~= nil then
print("showTextListener")
myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
timer.performWithDelay(1000, hideMyText, 1 )
end
end


So, your listener will executes only if myText is not created yet. Or to this, if you want to recreate myText object every tap.

local function showTextListener(event)
if myText then myText:removeSelf() ; myText = nil end
if event.phase == "began" then
print("showTextListener")
myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
timer.performWithDelay(1000, hideMyText, 1 )
end
end


When you call obj:removeSelf(), it removes corona metatable from object and remove it from display hierarchy. But the object is not completely removed after this, it becomes a simple lua table {}. So you must set it to nil, to the garbage collector deleted it completely.