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

How do I get this to repeat 3 times?

I'm trying to have this play a different songs 3 times after the first one ends... What am I doing wrong? (This is only part of the script)

local randIndex = math.random(1, #songs.titles);
	local title = songs.titles[randIndex];
	local id = songs.ids[randIndex];
	print("Trying to play")
	music:Stop()
	wait(0.01)
	music.SoundId =("http://www.roblox.com/asset/?id="..id)
	print("Now playing: "..title)
	music:Play()	
	wait(0.01)
	for i=1,3 do
		local randIndex = math.random(1, #songs.titles);
		local title = songs.titles[randIndex];
		local id = songs.ids[randIndex];
		print("Trying to play")
		music:Stop()
		wait(0.01)
		music.SoundId =("http://www.roblox.com/asset/?id="..id)
		print("Now playing: "..title)
		music:Play()	
		wait(0.01)
		repeat wait() until music.Ended:connect()
	end
	print("Lol")
	

2 answers

✓ Accepted answer

Your code assumes the Ended event returns a boolean. By definition, events don't return values. It would be best for you to set a flag when the song ends:

local songIsEnded = false;

You'd then set that flag to true when the "Ended" event is triggered:

music.Ended:connect(function()
	songIsEnded = true;
end)

Then in your loop you'd have:

repeat wait() until songIsEnded
-- Reset the flag
songIsEnded = false;

4 comments

0

OOh, couldn't you repeat wait() until music.Ended:connect(function() return true end) ?

0

@BobserLuck I assume that would probably work. The only issue with that approach is that would add a Ended event listener to music every single frame, which is very, very inefficient. This is assuming Rbx.Lua isn't smart enough to not instantiate multiple event listeners that do the exact same thing, but I doubt it is.

0

Good point. You could have a longer wait but having one event listener is enough. I was just wondering if it could work.

0

The wait time would be miniscule. We're talking nanoseconds.

Hmmm.... This isn't the best thing but instead of using repeat wait() until music.Ended:connect() try:

t=0
repeat
wait(1)
t=t+1
until t>music.TimeLength

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