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

How do you restart a for loop?

Asked by
ItsMeKlc 235 Moderation Voter
8 years ago

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
0
Why don't you want to make it a function? Redbullusa 1580 — 8y
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) ItsMeKlc 235 — 8y
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. Redbullusa 1580 — 8y

2 answers

Log in to vote
1
Answered by 8 years ago

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.
0
Go with this, much better than mine :) Codebot 85 — 8y
0
Thanks! But is there any way to do it without making it a function? ItsMeKlc 235 — 8y
0
None that I know of, or it will be a complex script. Could you mark it as an answer? HungryJaffer 1246 — 8y
0
Gonna leave it up a bit longer to see if anyone knows how to do it without having to make it a function ItsMeKlc 235 — 8y
0
Oh, ok. HungryJaffer 1246 — 8y
Ad
Log in to vote
0
Answered by
Codebot 85
8 years ago

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

Answer this question