17

So I'm trying to create a little something and I have looked all over the place looking for ways of generating a random number. However no matter where I test my code, it results in a non-random number. Here is an example I wrote up.

local lowdrops =  {"Wooden Sword","Wooden Bow","Ion Thruster Machine Gun Blaster"}
local meddrops =  {}
local highdrops = {}

function randomLoot(lootCategory)
    if lootCategory == low then
        print(lowdrops[math.random(3)])
    end
    if lootCategory == medium then

    end
    if lootCategory == high then

    end
end

randomLoot(low)

Wherever I test my code I get the same result. For example when I test the code here http://www.lua.org/cgi-bin/demo it always ends up with the "Ion Thruster Machine Gun Blaster" and doesen't randomize. For that matter testing simply

random = math.random (10)
print(random)

gives me 9, is there something i'm missing?

user2677006
  • 173
  • 1
  • 1
  • 4

1 Answers1

28

You need to run math.randomseed() once before using math.random(), like this:

math.randomseed(os.time())

One possible problem is that the first number may not be so "randomized" in some platforms. So a better solution is to pop some random number before using them for real:

math.randomseed(os.time())
math.random(); math.random(); math.random()

Reference: Lua Math Library

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Running an updated version of my code with that line seems to do the trick on this lua code demo here http://www.lua.org/cgi-bin/demo however , running the same code on my lua eclipse ide gives me the same original problem I was having, it doesen't seem to be randomizing, could it be a problem with my IDE? – user2677006 Aug 13 '13 at 03:18
  • 1
    @user2677006 Try calling `math.random()` once right after `math.randomseed()`, see if it's fixed. – Yu Hao Aug 13 '13 at 03:34
  • This seemed to fix the problem, how I do not know for sure but thank you very much. – user2677006 Aug 13 '13 at 03:41
  • I just ran into this problem and curious why this is happening. Anybody? – deathemperor Aug 12 '15 at 13:28
  • 1
    @deathemperor [Why is the first random number after randomseed() not random?](http://lua-users.org/lists/lua-l/2007-03/msg00564.html) – Yu Hao Aug 12 '15 at 13:42