How to design a button, which its touch event listener will generate another button with the same listener?

Hi,

I am new to learning programming and I have a code structure problem.

Let’s say I am creating a button, which when I press it, will print(“hello world”), and at the same time, generate another new button, which will also print(“hello world”) and generate yet another new button … so on.

My code structure is something like this:

function sayHelloAndGenerateNewButton()

    print(“hello world”)

    a = display.newImage(“button.png”, randomx, randomy)

    a:addEventListener(“touch”, sayHelloAndGenerateNewButton)

end

button1 = display.newImage(“button.png”, randomx, randomy)

button1:addEventListener(“touch”, sayHelloAndGenerateNewButton)

My problem is that red line of code. In a function, I cannot write a line of code which call the function itself.

How do I get around this problem? 

Regards

Alex Chong

This would work

-- Forward declare listener and builder (don't use globals) local onTouch local newButton -- Current y position for next button local curY = 50 onTouch = function( self, event ) if( event.phase == "ended" ) then newButton() display.remove(self) print("Hello world") end newButton = function() local button = display.newRect( 0, 0, 100, 40 ) button.x = display.contentCenterX button.y = curY curY = curY + 50 button.touch = onTouch button:addEventListener("touch") end newButton()

Thank you it works. 

Just learnt something new here - FORWARD DECLARING the variables.

This would work

-- Forward declare listener and builder (don't use globals) local onTouch local newButton -- Current y position for next button local curY = 50 onTouch = function( self, event ) if( event.phase == "ended" ) then newButton() display.remove(self) print("Hello world") end newButton = function() local button = display.newRect( 0, 0, 100, 40 ) button.x = display.contentCenterX button.y = curY curY = curY + 50 button.touch = onTouch button:addEventListener("touch") end newButton()

Thank you it works. 

Just learnt something new here - FORWARD DECLARING the variables.