请考虑以下lua代码段:
local time = os.time()
for _= 1, 10 do
time = time + 1
print('Seeding with ' .. time)
math.randomseed(time)
for i = 1, 5 do
print('\t' .. math.random(100))
end
end
Run Code Online (Sandbox Code Playgroud)
在Linux机器上,结果如预期的那样是随机数.但似乎至少在Mac OS X上,改变种子后的第一个随机数总是一样的!
我猜这与Lua依赖C rand()函数生成随机数这一事实有关,但有人有解释吗?
编辑:这是linux机器上面代码输出的摘录(即输出是预期的):
$ lua test.lua
Seeding with 1232472273
69
30
83
59
84
Seeding with 1232472274
5
21
63
91
27
[...]
Run Code Online (Sandbox Code Playgroud)
在OS X机器上,"Seeding with ..."之后的第一个数字始终为66.
我正在研究一个随机化数字的代码.我把它math.randomseed(os.time())
放在一个循环中.代码如下:
for i = 1, 1000 do
math.randomseed( os.time() )
j = math.random(i, row-one)
u[i], u[j] = u[j], u[i]
for k = 1, 11 do
file:write(input2[u[i]][k], " ")
end
file:write"\n"
end
Run Code Online (Sandbox Code Playgroud)
当我多次运行时,整个输出总是一样的.重新运行时,随机种子不应该阻止重复吗?
如何生成每次运行脚本时都不同的随机整数?我目前正在做一个“不可能的测验”,它使用随机数从表格中选择一个问题。每次我运行脚本时,问题的顺序都是相同的。我还使用 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 …
Run Code Online (Sandbox Code Playgroud)