1. 程式人生 > >lua 中隨機種子的設定

lua 中隨機種子的設定

1. 常用的方法:

math.randomseed(os.time())
print(math.random())

2. 改進的方法:

math.randomseed(tostring(os.time()):reverse():sub(1, 6))
print(math.random())

3. 再改進的方法:

local socket = require("socket") -- 需要用到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())
print(math.random())

ref: http://blog.csdn.net/zhangxaochen/article/details/8095007