I don’t know why this even happens. There’s literally no reason why this should be happening that I can think of, it feels like a glitch in Roblox Studio or something.
local speed = math.random(0.5, 1)
print(speed) -- prints as 0
When speed is printed, it shows as 0. There is literally no other place in the script that uses this variable and already it’s broken. Can anyone please explain why this is happening and how to fix it?
This is because when math.random is called with arguments it will return an integer within that range and it looks like if you input decimals it make it an integer.
If you are looking for a decimal between that range you should do something like
Yep, This is how it does it behind the scenes
Only when there is no arguments will it return a random decimal, and when numbers are provided it will return an integer.
Code
switch (lua_gettop(L))
{ // check number of arguments
case 0:
{ // no arguments
// Using ldexp instead of division for speed & clarity.
// See http://mumble.net/~campbell/tmp/random_real.c for details on generating doubles from integer ranges.
uint32_t rl = pcg32_random(&g->rngstate);
uint32_t rh = pcg32_random(&g->rngstate);
double rd = ldexp(double(rl | (uint64_t(rh) << 32)), -64);
lua_pushnumber(L, rd); // number between 0 and 1
break;
}
case 1:
{ // only upper limit
int u = luaL_checkinteger(L, 1);
luaL_argcheck(L, 1 <= u, 1, "interval is empty");
uint64_t x = uint64_t(u) * pcg32_random(&g->rngstate);
int r = int(1 + (x >> 32));
lua_pushinteger(L, r); // int between 1 and `u'
break;
}
case 2:
{ // lower and upper limits
int l = luaL_checkinteger(L, 1);
int u = luaL_checkinteger(L, 2);
luaL_argcheck(L, l <= u, 2, "interval is empty");
uint32_t ul = uint32_t(u) - uint32_t(l);
luaL_argcheck(L, ul < UINT_MAX, 2, "interval is too large"); // -INT_MIN..INT_MAX interval can result in integer overflow
uint64_t x = uint64_t(ul + 1) * pcg32_random(&g->rngstate);
int r = int(l + (x >> 32));
lua_pushinteger(L, r); // int between `l' and `u'
break;
}