1

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.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
math.random
  • 99
  • 2
  • 10
  • 1
    possible duplicate of [Lua choose random item from table](http://stackoverflow.com/questions/2988246/lua-choose-random-item-from-table) – Adam Mar 02 '15 at 17:42
  • Both answers from [Lua choose random item from table](http://stackoverflow.com/questions/2988246/lua-choose-random-item-from-table) don't works with letters. – math.random Mar 02 '15 at 17:55

1 Answers1

3

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) 
lhf
  • 70,581
  • 9
  • 108
  • 149
  • 1
    @math.random, if you want letters, use `section = {"a", "b", "c", "f", "z"}`. – lhf Mar 02 '15 at 18:13
  • i need this to load a random .png. This is the code: `love.graphics.newImage("/Images/a.png") .... love.graphics.newImage("/Images/b.png") love.graphics.draw(section[imath.random(#section)], x, y)` – math.random Mar 02 '15 at 18:25