如何生成每次运行脚本时都不同的随机整数?我目前正在做一个“不可能的测验”,它使用随机数从表格中选择一个问题。每次我运行脚本时,问题的顺序都是相同的。我还使用 table.remove() 在提出问题后从表中删除问题。然而,一旦被删除,它就会继续问同样的问题,因为它没有选择一个新的随机数(我正在使用 math.random(1, #Questions) 从“问题”表中选择一个随机问题.)
local lives = 3
Questions = {
{"What is the magic word?", "lotion"},
{"Does anyone love you?", "no"},
{"How many fingers do you have?", "10"},
{"What is 1 + 1?", "window"}
}
function lookForAnswer(ans)
table.remove(Questions[number])
local input = io.read() tostring(input)
if input:lower() == ans then
return true
end
lives = lives - 1
if lives <= 0 then
exit()
end
return false
end
for i = 1, #Questions do
number = math.random(1, #Questions)
local q = Questions[number][1]
local a = Questions[number][2]
print(q)
if lookForAnswer(a) then
print("Correct!\n")
else
print("WRONG! Lives: " .. lives .. "\n")
end
end
io.read()
您需要通过调用来播种随机数生成器math.randomseed()
打电话之前math.random()
。使用起来很常见os.time()
作为种子值(math.randomseed(os.time())
).
重要的是要注意math.random()
是确定性的,因此熵必须来自种子值。如果将相同的值传递给种子,您将获得相同的值math.random()
. Since os.time()
仅分辨率低至秒,这意味着如果您在给定秒内多次调用该命令,您将得到相同的值。您可以尝试使用更多熵源进行播种(/dev/random
) 如果你喜欢。
需要澄清的是,如果它是真正随机的,您不能保证每次值都会不同。您所能做的就是确保获得相同值的概率足够低。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)