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

Loop within a Loop?

Asked by 8 years ago

Is it possible to loop within a loop? If so, what exactly does that do in terms of operation

Like, for example does it do this:

Loop1() Loop2() end end

Starts loop1 variables of loop1 transfer to loop2 then starts loop 1 again repeat() or is it independent loop1() loop2() end end

Starts loop1 , loop until nil, then start loop2, loop until nil. . I need to make a loop that can iterate through a list of players then

on a specific player iterate through a table and add values to the specific player via a sever script so I need to understand how loops function.

0
Thank you soooo Much. I have been looking for this. SamDomino 65 — 8y
0
Glad to help :) BlackJPI 2658 — 8y

1 answer

Log in to vote
2
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

Nesting

It is possible and actually used incredibly frequently in programming. The technique is referred to as nesting. First lets think about what exactly a loop does:

All the the loops in Lua work in a very similar way where they complete a list of steps, one at a time, until it reaches the end where the loop then dictates whether or not the steps should be repeated again.

Now lets stick a loop inside of that loop. The loop starts processing the steps one by one until it gets to the nested loop. Now this loop has to go through all of it's steps, looping as many times as it needs too, until the condition is no longer met or the loop is broken. Now we're back into the original loop completing instructions once again. When the end of this loop is reached, it loops back over everything inside of it, including the nested loop.

So lets say we were given the following numeric for loop with another nested for loop inside:

for a = 1, 3 do
    print(a)
    for b = 1, a do
        print("Hello")
    end
end

What would the output look like? Remember that everything inside first for loop must be run completely before it can start the loop again.

Output:

1
Hello
2
Hello
Hello
3
Hello
Hello
Hello

As you can see, everything inside the first for loop is executed before the loop starts again, including the entire nested for loop.

This applies for all loops in Lua (for, while, and repeat).

For your problem

To accomplish your task, we loop through all the players and if the player is indeed the specific player then we loop through the table.

local specificPlayer = "Player"
local array = {} -- Things to loop through

for _, player in next, game.Players:GetPlayers() do
    if player.Name == specificPlayer then
        for _, value in next, array do
            -- Do Stuff
        end
    end
end
Ad

Answer this question