lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

If you want to randomize your numbers further - not only using seconds
time, you could do that:

local tstart = os.clock()
local hashsource = (tstart..os.time().."some other string (hostname?)"):rep(100)
local hash = 0
for i=1,#hashsource do
  local a = hashsource:byte(i,i)
  for j=1,#hashsource do
    local b = hashsource:byte(j,j)
    local h = a*0x10000+b
    hash = (hash + h)%(0xffffffff+1)
local t = os.clock() - tstart
hash = (hash + math.floor(t*0x10000)+os.time())%(0xffffffff+1)
print("seed: ",hash)

The os.clock function returns the number of seconds (with about 5
millisecond precision) that your application has used up (processor
time - as far as I know). So if you make some somewhat complex
calculations, it'll be somewhat random how long it takes, depending on
the machine that runs, other processes, etc. (since some wlan drivers
nowadays do some kind of processing on the CPU (my netbook slows down
if the connection is bad), this is supposed to take different times
now and then).

But of course, as others have pointed out: the math.random function is
of poor quality, so if you need really good random numbers, use a
library that is supposed to return good random numbers.


2010/1/17 Alex Davies <>:
> Majic wrote:
>> But if you're executing the script, in it's entirely, more than once a
>> second you're randomseed()'ing with the same time in that second and
>> you'll get the same random numbers...
> Well if you're not able to have a "RunOnce"or "Init" function, then add this
> to your script:
> if not Seeded then
>  math.randomseed(os.time())
>  Seeded = true
> end
> Unless you're also running each script in its own little sandbox without
> access to globals, in which case perhaps that is a problem..
> You should know though that whilst each sequence of random() numbers are
> supposed to be random, no guarantee is given that two sequences from seeds
> that are very similar (ie differ by 1) won't share patterns.  A fair few
> generators fail there (Delphi's math library comes to mind) - sometimes
> re-randomseeding with a random number produced by the sequence a few times
> can separate the seeds out a bit.  Whether or not your C compiler suffers
> this, who knows.  ie:
> math.randomseed(os.time())
> for i = 1,4 do
>  math.randomseed(math.random(2^31))
> end
> It's every bit a hack as it looks too.
> - Alex