lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I was doing some testing that involved generating very large random integers and I noticed a bug in Lua 5.3.4's math.random(). If you pass in a range larger than 2^31-1 (L_RANDMAX), math.random() will generate random integers that only have 31 bits of randomness. For example, this code will run without errors:

    for _=1,1000000 do
        assert(math.random(0, 0x7fffffffffffffff) & 0xffffffff == 0)
    end
    print("The lowest 32 bits were always zero!")

The fix for this is pretty simple:

** $Id: lmathlib.c,v 1.119 2016/12/22 13:08:50 roberto Exp $
269,270c269
<   luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
<                    "interval too large");
---
  luaL_argcheck(L, up - low + 1 <= L_RANDMAX, 1, "interval too large");

which makes math.random(0, 0x7fffffffffffffff) produce an interval-too-large error. Also, the documentation would need to be updated to reflect this constraint (it currently just says: "The value n-m cannot be negative and must fit in a Lua integer.").

Or, alternatively, the C code could be changed to use multiple calls to l_random() to produce fully random integers from larger ranges, which would introduce some additional complexity, but might be a good idea anyway.