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

How do you loop through a table but each time it loops it's looped in a different order?

I'm working on a project where there are these lines of code that scroll through each player in game.Players, but in a certain order. Is there a way for that order to be random?

[EDIT] I hope this isn't too vague, but here's a simple script I made about the problem.

while true do
	for i,v in pairs (game.Workspace.Folder) do
		print(v.Name)
		-- I don't want it to go through the whole folder, but I want it to go through it in a random order.
	end
end

1 comment

0

Please edit your question to include the script in question.

1 answer

✓ Accepted answer

You could make a table of random indexes, and check if the index exists, to know to add it or not. Then, repeat that until the table has the correct length, and loop through. Example implementation:

function rpairs(Table)
	local function Contains(Table, Item)
		for i,v in ipairs(Table) do
			if v == Item then return true end
		end
		return false
	end
	local Result = {}
	local Indexes = {}
	repeat
		local Index = math.random(1, #Table)
		if not Contains(Indexes, Index) then
			table.insert(Indexes, Index)
		end
		until #Indexes == #Table
	for _, i in ipairs(Indexes) do
		table.insert(Result, Table[i])
	end
	return ipairs(Result)
end
-- iterate through table:
for i,v in rpairs(game.Workspace.Folder:GetChildren()) do
	print(v)
end

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