Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I get this to repeat 3 times?

Asked by
ItsMeKlc 235 Moderation Voter
8 years ago

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

Log in to vote
0
Answered by 8 years ago

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;
0
OOh, couldn't you repeat wait() until music.Ended:connect(function() return true end) ? BobserLuck 367 — 8y
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. DreadPirateRobux 655 — 8y
0
Good point. You could have a longer wait but having one event listener is enough. I was just wondering if it could work. BobserLuck 367 — 8y
0
The wait time would be miniscule. We're talking nanoseconds. DreadPirateRobux 655 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

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

Answer this question