Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can't randomize values in a table?

local Maps = game.ServerStorage.Maps:GetChildren()
local collected = {}

for count = 1, 3, 1 do
	local Picked = tostring(Maps[math.random(1,#Maps)])
	if #collected <= 3 then
		if collected[Picked] == nil then
			collected[#collected+1] = Picked
		else
			collected[#collected+1] = tostring(Maps[math.random(1,#Maps)])	
		end
	end
end

print(collected[1])
print(collected[2])
print(collected[3])

Basically I'm trying to get it to print 3 different and randomized map names, but sometimes it gets a map twice... Is there's a way to fix it?

1 answer

✓ Accepted answer

There are two problems here:

  1. You’re searching for collected[Picked] but you’re always setting the value, not the index, to the map name.

  2. Even if you fix this, there is a chance that the random map from the else block is still counted for! You have no check for this!

You can use table.find() to solve the first problem and a conditional loop for the second part:

while collected < 3 do
    local picked = Maps[math.random(#Maps)]
    if not table.find(collected, picked) then
        table.insert(collected, picked)
    end 
end

This discussion is preserved as it was. New answers, comments, and votes are closed.