Lua math.randomseed返回相同的值

时间:2018-10-04 19:27:59

标签: lua openresty

这里是随机生成器

local hexset = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8','9', 'a', 'b', 'c', 'd', 'e', 'f'
}

function random_hex(length)
    math.randomseed(os.time())

    if length > 0 then
        return random_hex(length - 1) .. hexset[math.random(1, #hexset)]
    else
        return ""
    end
end

print(utils.random_hex(32))
print(utils.random_hex(32))
print(utils.random_hex(32))
print(utils.random_hex(32))

4个print给我完全相同的RequestSid:

46421938586706fff767d26410f524ee
46421938586706fff767d26410f524ee
46421938586706fff767d26410f524ee
46421938586706fff767d26410f524ee

我在我的openresty应用中使用它。我也尝试在lua顶层设置一次math.randomseed(os.time())。然后,在进行100个并发调用之后,我得到大约6个重复的十六进制。

2 个答案:

答案 0 :(得分:2)

math.randomseed首先接受它的参数并将其转换为整数。 os.time()的整数部分通常每秒更改一次,因此使用这种方法一秒钟将获得相同的随机值序列。

您可能不想重复设置随机种子。在程序开始时设置一次就足够了(尽管math.random可能不是非常高质量的随机数生成器)。

答案 1 :(得分:1)

math.randomseed(os.time())移出您的功能,它应该可以正常工作。

local hexset = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8','9', 'a', 'b', 'c', 'd', 'e', 'f'
}

math.randomseed(os.time())

function random_hex(length)
    if length > 0 then
        return random_hex(length - 1) .. hexset[math.random(1, #hexset)]
    else
        return ""
    end
end

print(random_hex(32))
print(random_hex(32))
print(random_hex(32))
print(random_hex(32))