Thought's on a script for Playlist

Hello Everyone, so when making my game Clash Of Roblox version Alpha 1.9, I thought of a process of making a playlist, something more efficient to not only write but have it actually function.

  1. This is in a local script, inside StarterGui but will function in StarterPlayer.

  2. Every player can get different songs playing for them in the background, and the script can be retrofitted with an option to disable it if needed.

  3. It is even able to function if it is Disabled and then Re-Enabled by other scripts.

If you have any thoughts to make it more efficient, please comment down below.

local Music = {script.Song1, script.Song2} --More songs can be added here.

function MusicPlay()
	local MusicChoice = math.random(1,#Music) 
	Music[MusicChoice]:Play() --Plays it.
end

for A,B in ipairs(Music) do --Checks all songs to see which one triggers a .Ended event
	B.Ended:Connect(function()
		MusicPlay() --Loops back to the function()
	end)
end

Music[2]:Play()--Jumpstart line, choose any of the songs in the table to play first, and every player that joins will hear it first.

PS: If Anyone notice’s that i’m posting a similar topic to this, please point it out, since I haven’t been able to spot any topics related to this whilst surfing the net.
PPS: Is this script valid to put in #resources:community-resources ? And if so, how?

Thank You :slightly_smiling_face:

5 Likes

Maybe in the math.random make so that the second value is added automatically, that is the length of the songs so math.random(1,#Music)

1 Like

Agreed, I will do that Mod right now.

Also is this the correct area for posting this? Since you guy’s are reviewing the code and it’s literally called Code Review.

Yes this is the correct category

1 Like

It’s usually best to use a traditional for loop instead of ipairs. Also make sure your variable names mean something instead of being arbitrary.

for i = 1, #Music do
   local Song = Music[i]
   Song.Ended:Connect(function()
      MusicPlay() --Loops back to the function()
   end)
end
1 Like

Could you explain why at all? Ipairs is faster anyway

2 Likes

Very good, don’t have any thoughts on how to make it better.

1 Like

From what i can see, this traditional loop goes in a certain order right? Like from song 1 all the way to song 2 or 3 etc?

The idea of the playlist was add an element of random chance, at least so the next song that plays isn’t predictable by players
(Yes there are some players who are nit-picky about it :sad:)

And ipairs() kinda works out faster too. But hey, whats your reasoning behind it? :slightly_smiling_face:

I guess ipairs is actually faster in luau. In traditional lua, it is much slower. I did some benchmarks and ipairs is suprisingly 50% faster than a traditional loop.

2 Likes

Ok, we do use luau, we don’t use the traditional Lua, so there’s no reason to switch to the traditional loop while it can be 50% faster