【问题标题】:Lua random number? [duplicate]Lua随机数? [复制]
【发布时间】:2014-03-15 10:23:42
【问题描述】:

如何在每次运行脚本时生成一个不同的随机整数?我目前正在做一个“不可能的测验”,它使用随机数从表格中选择一个问题。每次我运行脚本时,问题的顺序都是一样的。我还使用 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()

【问题讨论】:

标签: random lua


【解决方案1】:

在调用math.random() 之前,您需要先调用math.randomseed() 来播种随机数生成器。使用os.time() 作为种子值(math.randomseed(os.time()))是很常见的。

请务必注意,math.random() 是确定性的,因此熵必须来自种子值。如果您将相同的值传递给种子,您将获得相同的值math.random()。由于os.time() 的分辨率只有几秒,这意味着如果您在给定的秒内多次调用该命令,您将获得相同的值。如果您愿意,可以尝试使用更多熵源进行播种 (/dev/random)。

澄清一下,如果它是真正随机的,你不能保证每次的值都会不同。您所能做的就是确保您获得相同值的概率足够低..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多