Lua random number? [duplicate]

2020-04-21 06:09发布

问题:

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()

回答1:

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()).

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.

best of luck to you.