Find a random number in Lua

I tried to use lua to generate a random number, but it just spit out the lowest value. For example, if I run:

 x = math.random(17,41) 
print(x)

It returns:

17

what happened?

Lua uses the C runtime library pseudo-random number generator. Its properties depend on your platform. For example, on some versions of Windows, the generator is always initialized at the same point in the pseudo-random sequence, so you can always get the same sequence of values ​​when you run the program (see http://msdn.microsoft.com/en-US /library/f0d4wb4t.aspx).

You can use math.randomseed to start a pseudo-random sequence elsewhere. Every time you run the program, you can use os.time to initialize it with a different value (Assuming that at least one second is allowed between runs).

Please also note that in some Windows C runtime libraries, the first result obtained after calling srand (or math.randomseed in Lua) A pseudo-random value is very dependent on the value you pass. So I recommend calling math.random once and ignoring its result after calling math.randomseed.

I tried to use Lua generates a random number, but it just spit out the lowest value. For example, if I run:

x = math.random(17,41) 
print(x)

It returns:

17

What’s wrong?

Lua uses the C runtime library pseudo-random number generator. Its properties depend on your platform. For example, on some versions of Windows, the generator The initialization is always done at the same point of the pseudo-random sequence, so the same value sequence can always be obtained when running the program (see http://msdn.microsoft.com/en-US/library/f0d4wb4t.aspx).

< /p>

You can use math.randomseed to start a pseudo-random sequence elsewhere. Each time you run the program, you can use os.time to initialize it with a different value (assuming that at least one second is allowed between runs) .

Please also note that in some Windows C runtime libraries, the first pseudo-random value obtained after calling srand (or math.randomseed in Lua) is very dependent on the value you pass. So I recommend calling math.random once and ignoring its results after calling math.randomseed.

Leave a Comment

Your email address will not be published.