Lua math.randomseed returns 相同值
Lua math.randomseed returns the same value
这是一个随机生成器
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 个重复的十六进制。
math.randomseed
首先接受它的参数并将其转换为整数。 os.time()
的整数部分通常每秒仅更改一次,因此使用这种方法您将在一秒钟内获得相同的随机值序列。
您可能不想重复设置随机种子。在程序开始时设置一次就足够了(尽管 math.random
可能不是一个非常高质量的随机数生成器)。
将 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))
这是一个随机生成器
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 个重复的十六进制。
math.randomseed
首先接受它的参数并将其转换为整数。 os.time()
的整数部分通常每秒仅更改一次,因此使用这种方法您将在一秒钟内获得相同的随机值序列。
您可能不想重复设置随机种子。在程序开始时设置一次就足够了(尽管 math.random
可能不是一个非常高质量的随机数生成器)。
将 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))