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

How to "jumble up" a table?

So, I'm making a music player. I'm looping through the sounds using a For Loop. This is my script,

local Music = script.Parent:WaitForChild("MusicFolder"):GetChildren()

while true do
	for i = 1,#Music do
		Music[i]:Play()
		Music[i].Ended:wait()
		wait(.5)
	end
end

On line 1, you'll notice I'm getting a table from a folder of sounds. The for loop on line 4 will play the sounds in order.

I'm doing this because I don't want the same sound to play more than once until all other sounds have been played.

So, my question is, how do I randomize the table? There may also be better ways of doing this that I'm unaware of. If there is, tell me.

Thank You

1 answer

✓ Accepted answer

If you just want to randomize a table, it's pretty easy. I use this particular function all the time:


--[[Randomizes the order of a table]]
function shuffle(tab)
	for i = 1, #tab- 1 do
	    local otherIndex = math.random(i, #tab) -- generate a random position
	    tab[i], tab[otherIndex] = tab[otherIndex], tab[i] --switch the cards
	end
end

After you randomize it, you can just loop through it again to play every sound only once

1 comment

0

I tested this, and it works great. Thank you m8.

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