Page 1 of 1
"math.random()" isn't all that random.
Posted: Wed Oct 06, 2010 2:15 am
by Kingdaro
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?
Re: "math.random()" isn't all that random.
Posted: Wed Oct 06, 2010 2:24 am
by TechnoCat
You should be setting a random seed before you generate random numbers.
People usually choose the current time at the start of execution.
Re: "math.random()" isn't all that random.
Posted: Wed Oct 06, 2010 3:35 am
by leiradel
TechnoCat wrote:You should be setting a random seed before you generate random numbers.
Also, math.random uses libc's rand which isn't very good on some system though for many games it will do well.
Re: "math.random()" isn't all that random.
Posted: Wed Oct 06, 2010 9:52 am
by zac352
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;
}
Re: "math.random()" isn't all that random.
Posted: Wed Oct 06, 2010 11:11 am
by Kingdaro
leiradel wrote:TechnoCat wrote:You should be setting a random seed before you generate random numbers.
Also, math.random uses libc's rand which isn't very good on some system though for many games it will do well.
Problem solved. Thanks