Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a Random number in lua [closed]

Tags:

random

lua

I am trying to use lua to produce a random number, but it simply spits out the lowest value. For instance, if I run:

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

It returns:

17

What is wrong?

like image 985
user2218101 Avatar asked Apr 28 '13 02:04

user2218101


2 Answers

That is not necessarily true. All random numbers are not entirely random. As an example, you can take a look at this working code; which is the same as you posted in question: http://eval.in/17806

The output as you can see is 38.

To quote from Doub's reply:

You can use math.randomseed to start the pseudo-random sequence elsewhere. You can use os.time to initialize that with a different value every time you run the program (assuming you allow at lease one second to elapse between runs).

Here is an example for the same program with randomseed in action: http://eval.in/17808

math.randomseed( os.time() )
x = math.random(17,41)  
print(x)
like image 68
hjpotter92 Avatar answered Nov 15 '22 09:11

hjpotter92


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 of the pseudo-random sequence, so you always get the same sequence of values when running your program (see http://msdn.microsoft.com/en-US/library/f0d4wb4t.aspx).

You can use math.randomseed to start the pseudo-random sequence elsewhere. You can use os.time to initialize that with a different value every time you run the program (assuming you allow at lease one second to elapse between runs).

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

like image 43
Doub Avatar answered Nov 15 '22 09:11

Doub