Why random math loops in my code?

Hi,

I was testing (learning) math.random functions, because later I’ll need it in my app.

Here’s my code:

local \_W = display.contentWidth   
local \_H = display.contentHeight  
  
-- add physics  
local physics = require( "physics" )  
physics.start()  
physics.setGravity( 0, -10 )  
  
-- add background  
local bg = display.newImage( "wood.jpg" )  
  
-- add options (for image sellection)  
local options = { "balloon\_blue.png", "balloon\_green.png", "balloon\_yellow.png", "balloon\_red.png" }  
  
-- display random balloon function  
function showBalloon ( event )  
local mr = math.random( 1, 4 )  
local balloon = display.newImage( options[mr], \_W / 2, \_H / 2 )  
physics.addBody( balloon, { density = 1, friction = 1, bounce = 1 } )  
end  
  
Runtime:addEventListener( "enterFrame", showBalloon )  

And this is what I see in simulator:

Instead of one random balloon image displayed (what I wanted and expected) I get millions of them (when balloon is a body) as you can see in the picture. If balloon is just an image, then the balloon flashes in all colors.

Can someone explain why? And how to fix this?
[import]uid: 46567 topic_id: 10333 reply_id: 310333[/import]

You’ve registered your “showBalloon” function as an event handler for the “enterFrame” event which gets called 30 times a second.

Try changing it to this to see the difference:

[code]

Runtime:addEventListener( “tap”, showBalloon )

[/code] [import]uid: 5833 topic_id: 10333 reply_id: 37691[/import]

Well, I don’t know the “technical” term for it, but that code of yours will constantly loop. That’s exactly the same code I use for my “main loop”:

----------------------------------------------------------------  
-- MAIN LOOP  
----------------------------------------------------------------  
local function main( event )  
 -- Do stuff  
end  
  
Runtime:addEventListener( "enterFrame", main )  

If you only want to do your function once, just call the function once without the event:

local \_W = display.contentWidth   
local \_H = display.contentHeight  
   
-- add physics  
local physics = require( "physics" )  
physics.start()  
physics.setGravity( 0, -10 )  
   
-- add background  
local bg = display.newImage( "wood.jpg" )  
   
-- add options (for image sellection)  
local options = { "balloon\_blue.png", "balloon\_green.png", "balloon\_yellow.png", "balloon\_red.png" }  
   
-- display random balloon function  
function showBalloon ()  
 local mr = math.random( 1, 4 )  
 local balloon = display.newImage( options[mr], \_W / 2, \_H / 2 )  
 physics.addBody( balloon, { density = 1, friction = 1, bounce = 1 } )  
end  
   
showBalloon()  

[import]uid: 11636 topic_id: 10333 reply_id: 37692[/import]

Or, do what Graham said! :slight_smile: [import]uid: 11636 topic_id: 10333 reply_id: 37693[/import]

It’s clear for me now, thanks :slight_smile: [import]uid: 46567 topic_id: 10333 reply_id: 37699[/import]