如何生成每次运行脚本时都不同的随机整数?我目前正在做一个“不可能的测验”,它使用随机数从表格中选择一个问题。每次我运行脚本时,问题的顺序都是相同的。我还使用 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()
Run Code Online (Sandbox Code Playgroud)
小智 5
您需要math.randomseed()在调用 之前通过调用 来为随机数生成器播种math.random()。os.time()用作种子值 ( )是很常见的math.randomseed(os.time())。
值得注意的是,这math.random()是确定性的,因此熵必须来自种子值。如果将相同的值传递给种子,您将获得相同的值math.random()。由于os.time()分辨率只有几秒,这意味着如果您在给定的秒内多次调用该命令,您将得到相同的值。/dev/random如果您愿意,您可以尝试使用更多熵源进行播种 ( )。
需要澄清的是,如果它是真正随机的,您不能保证每次值都会不同。您所能做的就是确保获得相同值的概率足够低。