Variable is set to something completely different after being set to something

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

local speed = 0.5 + math.random() / 2
Techincal Details

In the luau Source there’s a switch statment with the number of arguments called with
https://github.com/luau-lang/luau/blob/cdd1a380dbf768f168910317e7576210afcd9552/VM/src/lmathlib.cpp#L226

1 Like

Ah I see. I could’ve sworn I’ve randomized decimals before but that might just be my terrible memory. I used this and it’s working fine now.

local speed = math.random(5, 10)
speed = speed/10

You can also use.

local random = Random.new()

speed = random:NextNumber(0.5, 1)

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;
    }

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.