lua随机数,伪随机,触动精灵生成真正的随机数

nLog("----------1----------")
math.randomseed(os.time())
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 

nLog("----------2----------")
math.randomseed(os.time())
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 

nLog("----------3----------")
for i = 1, 5 do 
    math.randomseed(os.time())
    nLog(i.."  "..math.random(0,100))
end 

nLog("----------4----------")
math.randomseed(tostring(os.time()):reverse():sub(1, 6)) -- 随机种子
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 

nLog("----------5----------")
local ts = require"ts"
local socket = require("szocket") -- 需要用到 luasocket 库 
local function get_seed() 
    local t = string.format("%f", socket.gettime())
    local st = string.sub(t, string.find(t, "%.") + 1, -1) 
    return tonumber(string.reverse(st))
end 
math.randomseed(get_seed()) 
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 

运行结果(建议用第五个,第四个不是说不好,谁用谁知道,详看最后一段代码,不排除本人使用方法不对)

----------1----------
1  33
2  93
3  11
4  19
5  29
----------2----------
1  33
2  93
3  11
4  19
5  29
----------3----------
2  33
1  33
5  33
3  33
4  33
----------4----------
1  11
2  15
3  98
4  69
5  33
----------5----------
1  26
2  94
3  46
4  8
5  52
local ts = require"ts"
local socket = require("szocket")
function get_seeda() 
    local t = string.format("%f", socket.gettime())
    local st = string.sub(t, string.find(t, "%.") + 1, -1) 
    return tonumber(string.reverse(st))
end 
function get_seedb() 
    return tostring(os.time()):reverse():sub(1, 6)
end 

--这段运行很完美
math.randomseed(get_seeda()) 
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 
math.randomseed(get_seeda()) 
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 

--这段运行结果重复
math.randomseed(get_seedb()) 
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 
math.randomseed(get_seedb()) 
for i = 1, 5 do 
    nLog(i.."  "..math.random(0,100))
end 

参考结果
1  13
2  45
3  77
4  43
5  8
1  98
3  63
2  16
4  56
5  82

--下面没写错,有时候顺序就是这么乱了
1  70
2  9
3  89
4  62
5  75
2  9
1  70
3  89
4  62
5  75
触动的TSLib库自带一个获取真随机数的函数(貌似调用获取的一个系统值,必须得打开隐私权限管理才可以用)
getRndNum() 
参考:
http://www.touchsprite.com/helpdoc#/doc?id=511
https://www.zybuluo.com/miniknife/note/293935#函数getrndnum-获取随机数

参考:
http://www.touchsprite.com/docs/5489
http://www.touchsprite.com/helpdoc#/doc?id=793
https://www.jianshu.com/p/108fe9cbc79a
https://blog.csdn.net/chuanyu/article/details/90636138
https://blog.csdn.net/Nice_66/article/details/100772886

你可能感兴趣的:(lua随机数,伪随机,触动精灵生成真正的随机数)