I believe he needs help with how to implement tables? Although he is using the buttons table just fine, but maybe someone helped him with that and now he needs help to understand the whole concept to add for other things.
Tables are simple
local balloons = {} --congratulations you have just created a table
Tables are simple
--these are just examples:
local balloons = { 5, 7, 13, 61 }
--if you were to print this
print( balloons[3] ) -- it would call the third stored value, in this case it would be 13
print( balloons[1] ) --it would be 5
print( balloons[4] ) --and of course it would be 61, simple enough.
Let’s add this to your code. I will also add a maxBall and minBall. Even though you could use other methods, this will be easier to understand and implement.
local buttons = {}
maxBall = 1
minBall = 1
local touchButton = function (event) -- function to handle touch events
local obj = event.target -- localise the button pressed
group:insert( obj )
if event.phase == "ended" then
if obj.id == 1 then -- if button with ID=1 is pressed
local balloon[maxBall] = display.newImage("red\_balloon.png")
balloon[maxBall].x = display.contentWidth/2
physics.addBody(balloon[maxBall], { bounce = 0.5, radius = 45, friction = 1.0} )
balloon[maxBall]:addEventListener("touch", moveBalloon)
balloon[maxBall]:addEventListener("swipe", moveBalloon)
group:insert( balloon[maxBall] )
maxBall = maxBall + 1
-- put your add balloons code here
--remember to add each one to the balloons table
elseif obj.id == 2 then
balloon[minBall]:removeSelf()
balloon[minBall] = nil
minBall = minBall + 1
end
end
end
local i = display.newImageRect("add\_button.png", 75, 75) -- load a button image, make it 60 pixels wide and 30 high
i.x = 580; i.y = 55 -- place it in the top corner of the screen
i:addEventListener("touch",touchButton) -- add the touch event listener
i.id = 1 -- give it an ID - this way we can re-use the touch listener for multiple buttons
buttons[1]= i -- add this button to the buttons table
group:insert( i )
local o = display.newImageRect("add\_button.png", 75, 75)
o.x = 675
o.y = 55
o:addEventListener("touch",touchButton)
o.id = 2
buttons[2] = o
So what this does is instead of:
--Instead of giving it a table number ourselves, we have a variable that starts at 1, in this case maxBall, and every time it creates a balloon then
maxBall = maxBall + 1
--Therefor the next time it creates a balloon maxBall will be 2, and it goes on and on, gradually increasing by 1
--Now for minBall it does the same, it starts at 1 and removes the first balloon and then goes on to become number 2.
I used o as button number 2 just to keep the code on par, but xnailbender is right, you do not want to use i and even o as a variable. But of course you can use anything you want. Hope this all makes sense
[import]uid: 77199 topic_id: 37026 reply_id: 145284[/import]