Electroshockist
Electroshockist

Reputation: 27

lua math.random first randomized number doesn't reroll

so I'm new to LUA and am writing a simple guess-the-number script, but I've found a weird quirk that happens with math.random and I would like to understand what's happening here.

So I create a random seed with math.randomseed(os.time()), but when I go to get a random number, like this:
correctNum = math.random(10) print(correctNum),
it always gets the same random number everytime I run it, unless I do it twice (irrespective of arguments given):
random1 = math.random(10) print(random1)
random2 = math.random(10) print(random2)
,
in which case the first random number will never reroll on every execution, but the second one will.

Just confused about how randomization works in LUA and would appreciate some help.

Thanks,
-Electroshockist


Here is the full working code:

math.randomseed(os.time())
random1 = math.random(10)
print(random1)

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

repeat
  io.write "\nEnter your guess between 1 and 10: "
  guess = io.read()
  if tonumber(guess) ~= random2 then
    print("Try again!")
  end
  print()
until tonumber(guess) == random2
print("Correct!")

Upvotes: 1

Views: 321

Answers (1)

Henri Menke
Henri Menke

Reputation: 10939

I guess you are calling the script twice within the same second. The resolution of os.time() is one second, i.e. if you are calling the script twice in the same second, you start with the same seed.

os.time ([table])

Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst (for a description of these fields, see the os.date function).

The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to date and difftime.

Furthermore you are rolling a number between 1 and 10, so there is a 0.1 chance that you are hitting 4 (which is not that small).

For better methods to seed random numbers, take a look here: https://stackoverflow.com/a/31083615

Upvotes: 1

Related Questions