0

Why do the runs of this function output the same number every time, and how would I fix?

function randomNumber()
    number = math.random()
    print(number)
end

randomNumber()
randomNumber()

EDIT: I want to be able to run this function twice, like this, and get a unique random number both times.

jjjhfam
  • 13
  • 2

1 Answers1

3

Looks like a seeding issue. Put this at the beginning:

math.randomseed( os.time() )

For more information: http://lua-users.org/wiki/MathLibraryTutorial

user1102901
  • 565
  • 1
  • 4
  • 12
  • Is there any way to make it generate a new seed whenever I want, instead of every second? – jjjhfam Aug 18 '15 at 01:21
  • `math.randomseed()` merely sets the seed it is given. `os.time()` returns the current time in seconds once, which is always unique and perfect for a seed. You can replace it with a specific number if you want your random numbers to be consistent over multiple runs. Check the linked url for more information. – user1102901 Aug 18 '15 at 01:29
  • I understand that, but by using os.time() I can only generate a unique random number once every second. – jjjhfam Aug 18 '15 at 01:41
  • Right, you can just have a global variable that starts at `os.time()` and increase it by one whenever you want to generate a new unique seed. – user1102901 Aug 18 '15 at 01:42
  • You can use any source of randomness. e.g. `math.randomseed((("I4"):unpack(assert(assert(io.open("/dev/urandom")):read(4)))))` – daurnimator Aug 18 '15 at 06:56
  • @jjjhfam I think you're under the assumption you need to do `math.randomseed( os.time() )` every time in your function. that's not needed. you need to put `math.randomseed( os.time() )` at the very top of your program. no need to change your seed every time – Ivo Aug 18 '15 at 11:16