Math.random running all fields

Hoping this is gonna be the last topic I open for this project :dizzy_face:

I’m working on a code that should create a random object between three object in a table. These object are actually functions that contains display objects.
one of these:

    local function createTopo(event) 
    mouse=display.newImageRect("img/mouse.png",107,87)
    mouse.x=display.contentWidth+10
    mouse.y=display.contentHeight-250
    table.insert(enemy, mouse)
    mouse.myName="mouse"
    physics.addBody( mouse, "static")
    mouse.enterFrame=enemyScroll
    Runtime:addEventListener("enterFrame", mouse)
    mouse.addedScore= false
    return mouse
    end	

Then I add these functions in the table inside another function

local function addEnemy()	
		enemyTable={createTopo(),  createTeschio(), createCloud()}
		local randomEnemy = math.random(#enemyTable)
end

And in the end in call addEnemy() in gameLoop() function which is called every 3 seconds.

Well, I can’t understand why it doesn’t work and actually all of the 3 object are created together at the same time.

When you create your enemyTable object you’re not storing three functions, you’re actually calling them and then storing the results of them.

Change it to something like this:

enemyTable={createTopo,  createTeschio, createCloud}
local creationFunction = enemyTable[ math.random(#enemyTable) ]
local randomEnemy = creationFunction()
1 Like

It works! I really appreciate your help, thank you !