jeppy7
jeppy7

Reputation: 134

How do I randomly select an object from a table in Lua?

I'm trying to add a function that randomly selects objects from the table targets. I read somewhere that you can use targets[math.random(#targets)], but when I do that, it doesn't just reset one of the targets regardless of resetTarget() call, and it doesn't actually make the next target random.

local targets    -- an array of target objects

local bomb = display.newImage("bomb.png")
local asteroid = display.newImage("asteroid.png")
local balloon = display.newImage("balloon.png")

targets = { bomb, asteroid, balloon }

function createTarget()
    for i = 1, #targets do
        local t = targets[i]
        t.x = WIDTH + 50   -- start slightly off screen to the right
        t.y = math.random(100, HEIGHT - 100)   -- at random altitude
    end
end

function resetTarget(obj)
    createTarget()
end

function detectHits()
        -- Do hit detection for ball against each target
    local HIT_SLOP = BIRD_RADIUS * 2  -- Adjust this to adjust game difficulty
    for i = 1, #targets do
        local t = targets[i]
        if math.abs(t.x - bird.x) <= HIT_SLOP 
                and math.abs(t.y - bird.y) <= HIT_SLOP then
            -- Hit
            isBomb(t)
            isAsteroid(t)
            isBalloon(t)
            resetTarget(t)
            updateScore()
        end
    end
end

Upvotes: 1

Views: 1460

Answers (1)

Jeremy
Jeremy

Reputation: 554

This will work but you will need a forward reference to currentTarget.

What is your function to target the random target?

local newTarget = function()
    local rand = math.random(1,#targets)
    currentTarget = target[rand]
    doSomething()
end

Upvotes: 5

Related Questions