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

Doing other things while a for loop is running?

So I have this for loop that counts for 175 seconds then runs the next function, how would I do functions during the for loop, but not 'in' said for loop

	for racewait = 175, 0, -1 do
		wait(1)
		game.Workspace.StartingLine.Timer.SurfaceGui.Time.Text = "Race time: "..racewait
		    for _, Player in pairs(game.Players:GetChildren()) do
        if Player:IsA("Player") then
            Player.PlayerGui.MainGui.TimeFrame.Timer.Text = "Race time: "..racewait
        end
	end
end

1 answer

✓ Accepted answer

What You Need

Due to the yield on line 2 inside of your loop, the code is going to wait until the loop is done running to process any further code. What you need to do is use coroutines to eradicate any yields between your loop and the oncoming function.


What Are Coroutines?

Coroutines are separate threads. To understand what a thread is think of it like this - the script is a thread. What a coroutine does is it creates a new thread, that runs at the same time as the script.. thus eradicating any yields betwixt the two. In basic terms - wait()'s are ignored for the rest of the script.


How Do I Use A Coroutine?

There are two ways that are normally gone about this.

  • 1) Using the coroutine.wrap function

    The coroutine.wrap function takes in a function as the argument(the code that you wish to make a coroutine) and returns a callable thread.

--Call the coroutine.wrap function, with arguments of a function
coroutine.wrap(function()
	wait(10)
	print('Hi')
end)() --Call the returned thread.

print('Bye')

The above code would print 'Bye', wait 10 seconds, then print 'Hi'. Whilst normally, because of the wait in the code.. it would wait 10 seconds, then print 'Hi' and 'Bye' consecutively.

  • 2) Using coroutine.create and coroutine.resume.

    The coroutine.create function takes in the arguments of a function, and returns a thread. The coroutine.resume function is needed to run this thread!

coroutine.resume(coroutine.create(function()
	wait(10)
	print('Hi')
end))

print('Bye')

The same results as example 1 would happen.


Applying Coroutines To Your Code

You need to wrap your loop in a coroutine usingthe coroutine.wrap function.

coroutine.wrap(function()
	for racewait = 175, 0, -1 do
		 wait(1)
		game.Workspace.StartingLine.Timer.SurfaceGui.Time.Text = "Race time: "..racewait
		for _, Player in pairs(game.Players:GetChildren()) do
			if Player:IsA("Player") then
				Player.PlayerGui.MainGui.TimeFrame.Timer.Text = "Race time: "..racewait
			end
		end
	end
end)()

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