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

How do you restart a for loop?

How can you get for loops to go back to the very begin? Example :

Kids  = model:GetChildren()
for i=1,#Kids do
print("Getting kids")
if i==#Kids then
print("Going back to the beginning")
--Restart code
end

end

3 comments

0

Why don't you want to make it a function?

0

Well due to the rest of my code, it would just be a lot easier to have the loop restart (What I have abover isn't the actual code, just an exsample)

0

But that's one of the points of a function. It's to make your scripting experience easier & more organized rather than repeating yourself. Your loop will restart anyways if the function is executed.

2 answers

✓ Accepted answer

##Firstly, let's tab this code.

Kids  = model:GetChildren()
	for i=1,#Kids do
		print("Getting kids")
		if i==#Kids then
			print("Going back to the beginning")
			--Restart code
		end
	end

#Recursives

Now, let me introduce you to something called a recursive. It's a pretty neat thing, and I'll give you the wiki definition.

Recursion is a form of looping, where a function calls itself, usually until a condition is met. Although recursion can be somewhat difficult to understand at first, it can result in much cleaner code.

So, let me explain how to do this in the form of your code. We have a function that runs the for loop. If the condition is meant for it to restart, then we will call the same function again.

#The Finished Code

function Kids() -- create the function Kids
Kids  = model:GetChildren()
	for i=1,#Kids do
		print("Getting kids")
		if i==#Kids then
			print("Going back to the beginning")
			return Kids() -- If the condition is met, do the function again. Otherwise, do not repeat.
		end
	end
end

Kids() -- start it up again.

5 comments

0

Go with this, much better than mine :)

0

Thanks! But is there any way to do it without making it a function?

0

None that I know of, or it will be a complex script. Could you mark it as an answer?

0

Gonna leave it up a bit longer to see if anyone knows how to do it without having to make it a function

0

Oh, ok.

Make it a function

Kids  = model:GetChildren()

function GetKids()
Kids  = model:GetChildren()
for i=1,#Kids do
print("Getting kids")
if i==#Kids then
print("Going back to the beginning")
end

end
end

And also add another function for every time you 'get kids'

while true do
wait(30) -- Lets say every 30 seconds you want to GetKids()
GetKids()
end

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