Math.random output is always 'invalid argument #1 to 'random' (interval is empty)'

This script should print a random players name who has played the game but it always errors and says ‘invalid argument #1 to ‘random’ (interval is empty)’

local service = game:GetService("DataStoreService")
local store = service:GetDataStore("PlayersWhoJoined")
local key = "MainList1"
local players = game.Players


players.PlayerAdded:Connect(function(player)
	store:UpdateAsync(key, function(old)
		old=old or {}
		old[player.Name] = player.Name
		
		return old
	end)
	local data = store:GetAsync(key)
	
	local Randplayer = math.random(#data)
	print(Randplayer)

end)

Doesn’t math.random need two parameters to return something? The minimum range, and the maximum range.

same error on line 36 (local randIndex = math.random(#data))

this is what the table looks like btw
image

Can you also print #data, it can’t be 0 or less.

EDIT: Seems like its the issue, since your keys arent intergers

so do u know how to fix the problem

You must use a custom function to count the amount of items.

Example:

local function tableLen(tbl)
    local i = 0
    for _, v in pairs(tbl) do i += 1 end
    return i
end

how to use the function in the script above

You should use tonumber() to convert stated strings into integers.

not tested
local service = game:GetService("DataStoreService")
local store = service:GetDataStore("PlayersWhoJoined")
local players = game.Players
local key = "MainList1"

players.PlayerAdded:Connect(function(player)
    store:UpdateAsync(key, function(old)
        old = old or {}
        old[player.UserId] = true
        return old
    end)
end)

while true do
    local data = store:GetAsync(key)
    if data then
        local playerIds = {}
        for playerId in pairs(data) do
            table.insert(playerIds, playerId)
        end
        if #playerIds > 0 then
            local randomIndex = math.random(1, #playerIds)
            local randomPlayerId = playerIds[randomIndex]
            local randomPlayer = players:GetPlayerByUserId(randomPlayerId)
            if randomPlayer then
                print(randomPlayer.Name)
            end
        end
    end
    wait(60)  -- maybe this will work
end

thanks but is there a way to pick a random player that is offline

You would have to make a datastore of the player ids/names of players that joined possible to a leaderboard style top 50 or more.