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

What exactly is "for i,v in pairs() do" used for?

Asked by 5 years ago

I see this line a lot, and I was curious about what it does and how I use it, maybe someone of you guys know it.

1 answer

Log in to vote
1
Answered by
BenSBk 781 Moderation Voter
5 years ago
Edited 5 years ago
for var_1, var_2 in pairs(t) do
    -- ...
end

iterates over all elements (in pairs) of table t (in an arbitrary order), assigning the key of each to var_1 and the value of each to var_2. Here's a more practical example:

-- Returns a table with indexes as keys and Players as values.
local players = game:GetService("Players"):GetPlayers()

-- Iterate over all Players, printing "<player> is in the server!" for each.
for _, player in pairs(players) do
    print(player .. " is in the server!")
end

The use of _ simply denotes a dummy variable for readability; we don't use it in our code, but we have to have it there (otherwise we couldn't receive the second variable, the Player).

Here, we are using a generic for statement. Generic for statements traverse all values that are returned by an iterator function. pairs(t) is really just just an iterator factory that returns next, t, nil. next is the iterator function, which happens to be a primitive Lua function. t is the invariant state; the thing that we will be iterating over/traversing, which does not change. nil is the initial value for the control variable. For every iteration, the generic for statement invokes next with <invariantstate>, <controlvariable> passed as arguments. If the function returns nil, the loop breaks. If not, the variables are assigned to its returned values, and the control variable is assigned to its first returned value. The full syntax of the generic for statement is:

for var_1, ..., var_n in f, s, v do
    -- ...
end

The generic for is very powerful. You can write your own iterator functions for it once you fully understand how it works.

You can learn more about how it works here and, if you feel confident, here.

I hope that this helped you!

Ad

Answer this question