Do you actually need a better randomseed?
Lua math.random (found a nice randomseed)
I've long been put out about how there didn't seem to be a way to get a decent randomseed in Lua—I mean, the system time return didn't have milliseconds (so in my view, the random function wasn't fully functional). I had searched long and hard for a solution, but to no avail.
So, while trying to figure out how to make a network game with LuaSocket, I randomly came across this solution (it requires LuaSocket, by the way):
[cc lang='lua']
require 'socket'
math.randomseed(socket.gettime()*10000)
print(math.random(100))
[/cc]
If you don't multiply it by 10000, it will convert that time into an integer, cutting off the milliseconds, and thus be no better than the regular os.time().
I tried this out and it works fairly well. It's still not perfect as the following code on my 2Ghz dual core AMD Athlon X-2 processor
[cc lang='lua']
for i=1,20 do
math.randomseed(socket.gettime()*10000)
print(math.random())
end
[/cc]
produced the following result,
[cc lang='bash']
0.16043688597178
0.16043688597178
0.16043688597178
0.51493899734455
0.51493899734455
0.51493899734455
0.51493899734455
0.51493899734455
0.51493899734455
0.87877474393639
0.87877474393639
0.87877474393639
0.87877474393639
0.87877474393639
0.2350731134578
0.2350731134578
0.2350731134578
0.2350731134578
0.2350731134578
0.2350731134578
[/cc]
but it's still a whole lot better, and usable as long as you're not changing the seed faster than my computer can do 3–6 calculations in Lua 5.1 (64-bit). Keep in mind that the random numbers generated from a single seed shouldn't repeat the same number like this. So, the following code should be perfect for 99% of the programs out there requiring a random function (using a twist on the example above):
[cc lang='lua']
math.randomseed(socket.gettime()*10000)
for i=1,20 do
print(math.random())
end
[/cc]
Anyway, I just thought I'd share. Enjoy, and let us know if you find/know a better way.
Note: in the poll up there, don't select Yes if the functionality is great but you just don't want to have to use LuaSocket. It's referring to a better randomseed than the LuaSocket one—sorry for not specifying these things in the poll.
Reprinted from:http://ubuntuforums.org/showthread.php?t=1324986