How do I make a button that spawns objects?

Hey guys, so I’m very new to corona, would be great if you could answer my question as simply as possible : ) Cheers.

So I want to make a button that when pushed a desired physics object spawns into the scene whilst still maintaining its physics properties I have set for it. I initially dont want the object to be on screen until I spawn it in. I then want to be able to create another button (a different button, not the same one) to delete said object from the scene. Then when I push the first button, it spawns back in and so on. I know how to create buttons using the widget library, but just not sure how to do the above.

Also another question, after I’ve managed to get a button to spawn objects, is there a way that only a limited number of objects can be spawned, i.e a button that spawns a block but will only work when pushed 3 times to get a maximum of 3 blocks on screen. Once scene is restarted, you can push the button 3 more times and get more 3 more blocks.

Cheers for your help.

For the button spawning:

local function spawn()

     enemy = display.newRect(_R + 50, _CY, 40, 40)

                enemy:setFillColor(0)

                enemy.hasBeenScored = false

                enemy.id = “enemy”

                physics.addBody(enemy, “dynamic”, {bounce = 0})

end

local button = widget.newButton{

       (Usual things go in here)

      onEvent = spawn

}

Hopefully this helps. 

_R and _CY were some globals I intend to change soon, they are for positioning.

For limiting the number of spawned objects to three, you could try inserting them into a table then checking the amount of items are in that table:

if #table == 3 then

–disable button, etc.

end 

I hope that helps you, I started lua last month and I am only 12 years old…

For the button spawning:

local function spawn()

     enemy = display.newRect(_R + 50, _CY, 40, 40)

                enemy:setFillColor(0)

                enemy.hasBeenScored = false

                enemy.id = “enemy”

                physics.addBody(enemy, “dynamic”, {bounce = 0})

end

local button = widget.newButton{

       (Usual things go in here)

      onEvent = spawn

}

Hopefully this helps. 

_R and _CY were some globals I intend to change soon, they are for positioning.

For limiting the number of spawned objects to three, you could try inserting them into a table then checking the amount of items are in that table:

if #table == 3 then

–disable button, etc.

end 

I hope that helps you, I started lua last month and I am only 12 years old…