Search code examples
arrayslualua-tablelove2d

Love2d: random element from table


I'm trying to get a item randomly from a table. I have searched online but all the code I have found didn't work. My table looks like this:

section = {a, b}
love.graphics.newImage("/Images/a.png")
love.graphics.newImage("/Images/b.png")     
love.graphics.draw(section[imath.random(#section)], x, y) 

I need a random item from this table.


Solution

  • Try this:

    item = section[math.random(#section)]
    

    In your example:

    section = {
       love.graphics.newImage("/Images/a.png"),
       love.graphics.newImage("/Images/b.png"),
    }    
    love.graphics.draw(section[math.random(#section)], x, y)