## "math.random()" isn't all that random.

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Kingdaro
Party member
Posts: 395
Joined: Sun Jul 18, 2010 3:08 am

### "math.random()" isn't all that random.

Every time I open my game, a function that should be generating RANDOM numbers is generating the same combination of numbers EVERY TIME. Here's the code to my randomizing function that randomizes the list:

Code: Select all

function tRandom(t)
local values = {}
for i=1, #t do
local n = #values+1
table.insert(values,math.random(n),t[i])
end
return values
end

town = tRandom({1,2,3,4,5,6,7,8})
I'm not sure if it's just my problem, but this is going to be a major snag in my game development, and I need it fixed. Is there any solution?
Attachments
scrolling_random_test.love
This is the .love file with the script in it. The code to the top-left is the number that's always generated.

TechnoCat
Inner party member
Posts: 1611
Joined: Thu Jul 30, 2009 12:31 am
Location: Denver, CO
Contact:

### Re: "math.random()" isn't all that random.

You should be setting a random seed before you generate random numbers.
People usually choose the current time at the start of execution.

Party member
Posts: 184
Joined: Thu Mar 11, 2010 3:40 am
Location: Lisbon, Portugal

### Re: "math.random()" isn't all that random.

TechnoCat wrote:You should be setting a random seed before you generate random numbers.

Code: Select all

math.randomseed( os.time() )
Also, math.random uses libc's rand which isn't very good on some system though for many games it will do well.

zac352
Party member
Posts: 496
Joined: Sat Aug 28, 2010 8:13 pm
Contact:

### Re: "math.random()" isn't all that random.

Code: Select all

static int lua_random (lua_State* L) {
int l=lua_tointeger(L,1);
int h=lua_tointeger(L,2);
int r=rand(); //standard C rand function. Comes with math library
if (r!=NULL && h!=NULL)
lua_pushnumber(L,(lua_Number)l+floor(h*r)); // floor is also a C function in math.h, I think
else
lua_pushnumber(L,(lua_Number) r);
return 1;
}

Kingdaro
Party member
Posts: 395
Joined: Sun Jul 18, 2010 3:08 am

### Re: "math.random()" isn't all that random.

math.randomseed( os.time() )