Search code examples
randomlualove2d

How to pick up a random key from a table in Lua?


I'm using this code to draw a random pics from this table

FishImages = {image1 = love.graphics.newImage("bg/fish1.png"),
            image2 = love.graphics.newImage("bg/fish2.png"),
            image3 = love.graphics.newImage("bg/fish3.png"),
            image4 = love.graphics.newImage("bg/fish4.png"),}

with this function love.graphics.draw({FishImages.image1#--I guess the modification is here },pos.x,pos.y)

so how to pick up a random key from a table in Lua ?


Solution

  • math.random(1,4) generates a random integer in the range 1 to 4. So you can use:

    FishImages['image' .. tostring(math.random(1,4))]