思路:利用/dev/random获得真随机数,以此作为种子,生成为随机数。测试过ios,android,linux,mac都可以正常获得随机数。
function getTrueSeed()
local file = io.open("/dev/random","r")
if not file then
print("cannot open /dev/random")
return
end
local trueSeed = ""
io.input(file)
local str = io.read(4)
for i = 1, #str do
local char = str:sub(i, i)
trueSeed = trueSeed .. string.byte(char)
end
io.close(file)
return trueSeed
end
math.randomseed(getTrueSeed())
for i=1,2 do
print(math.random())
end
/dev/random 与 /dev/urandom 都是从linux主熵池中获取噪声生成的伪随机数。/dev/urandom 可能更要好一点,不阻塞。网上说的/dev/random 阻塞但质量更高这点待考证。
下图为linux4.8后的简化示意图: