Lua随机数? [英] Lua random number?

查看:100
本文介绍了Lua随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成每次运行脚本都不同的随机整数?我目前正在做一个不可能的测验",它使用一个随机数从一个表中选择一个问题.每次我运行脚本时,问题的顺序都相同.我也使用table.remove()将问题从表中删除.但是,一旦删除它,它仍然会问相同的问题,因为它没有选择一个新的随机数(我正在使用math.random(1,#Questions)从"Questions"表中选择一个随机问题)

How do I generate a random integer that is different every time I run the script? I am currently making an 'impossible quiz' that uses a random number to pick a question from a table. Every time I run the script, the questions are in the same order. I also use table.remove() to remove the question from the table once it has been asked. However, it continues to ask the same question once it has been removed, because it isn't picking a new random number (I'm using math.random(1, #Questions) to pick a random question from the 'Questions' table.)

    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.random( ).通常使用 os.time()作为种子值( math.randomseed(os.time())).

You'll want to seed your random number generator by calling math.randomseed() before calling math.random(). It's pretty common to use os.time() as the seed value (math.randomseed(os.time()).

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

It's important to note that math.random() is deterministic so the entropy has to come from the seed value. If you pass the same value to the seed you'll get the same value(s) math.random(). Since os.time() only has resolution down to seconds which means that if you invoke the command multiple times within a given second you'll get the same values back. You can try using more entropic sources for seeding (/dev/random) if you like.

为了澄清,您不能保证每次都是真正随机的值都会有所不同.您所要做的就是确保您获得相同值的可能性非常低.

And just to clarify, you can't guarantee that the values will be different every time if it's truly random. All you can do is ensure that there's a sufficiently low probability that you'll get the same values.

祝你好运.

这篇关于Lua随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆