I’m using the following code to give me a random number:
local id = math.random(1,2000000000)
This number is used to then find the ROBLOX player associated with that number ( or id, i guess you could call it)
My Issue is that (according to google) there are over 6.4 billion ROBLOX accounts, and when I try and do math.random with any number higher than 2 billion I get this error:
ServerScriptService.Server:10: invalid argument #2 to 'random' (interval is empty)
If needed here is the full script:
local rep = game:GetService("ReplicatedStorage")
local invoke = rep.RemoteFunction
local rt = require(script.r)
invoke.OnServerInvoke = function(player)
local Table = {}
--local picked = game.Players:GetNameFromUserIdAsync(id)
for i = 1, 5 do
local id = math.random(1,6000000000)
local rid = rt.fr(id)
table.insert(Table, rid)
end
return Table
end
How can I fix this? Or is there a better way of doing it?
The error you’re encountering occurs because the math.random function in Lua
only supports generating random numbers within the 32-bit integer range,
which is approximately between -2,147,483,648 & 2,147,483,647.
When you try to use a larger range, like 1 to 6,000,000,000, it exceeds this limit.
The solution to generate a number in a larger range is to combine two math.random calls.
local function random_large_number(min, max)
local range = max - min
local first_half = math.random(0, math.floor(range / 2))
local second_half = math.random(0, math.floor(range / 2))
local result = min + first_half * (math.floor(range / 2) + 1) + second_half
return result
end
-- Example usage:
local id = random_large_number(1, 6000000000)
Yes, using Random.new() will work for generating large numbers. Random.new() creates a random object, which provides a more flexible and reliable way to generate random numbers, and it doesn’t suffer from the 32-bit integer limit that math.random has.
local randomGenerator = Random.new()
for i = 1, 5 do
local id = randomGenerator:NextInteger(1, 6000000000)
local rid = rt.fr(id)
table.insert(Table, rid)
end