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

How For loops match up with Pairs? [closed]

Asked by
emite1000 335 Moderation Voter
10 years ago

I have read through how for loops work, and I understand it. But when I try to match up that knowledge with what people say about pairs, it doesn't make sense.

For example, the easiest explanation of pairs that I could somewhat understand that I found was this.

a={"This","is","an","Example"}

for k,v in pairs(a) do

print(v)    

end

According to how For loops are supposed to work, k is the starting value and v is the ending value. But why does printing v print out this is an Example? V is the ending value, it can't/hasn't been defined as anything?

I am just really confused. Can someone explain to me in simple terms how this stuff matches up?

Locked by OniiCh_n, TofuBytes, and BlueTaslem

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
3
Answered by
Ekkoh 635 Moderation Voter
10 years ago

There are two kinds of for loops:

¤ Enhanced for loops / foreach loops

¤ Numeric for loops

What you used was a foreach loop. Often times, k and v are used in foreach loops to represent key and value. If you don't know what a key and value looks like,

local t = { name = "emite1000" }
-- where `t` is the table, `name` is the key, and `"emite1000"` is the value.

To my knowledge, the pairs iterator will go through each key and value so you can work with each one, but a lot of times the key is disregarded because it is not needed (in which case, some people like to use _ rather than k to signify that it isn't important).

for _, v in pairs(Players:GetPlayers()) do
    v:Kick() -- in this example, only the value is used.
end

With your example, the keys in table a are automatically numeric because you didn't explicitly set them. So essentially your table also looks like this:

a={[1]="This", [2]="is", [3]="an", [4]="Example"}

Which means, printing the key and value like so...

for k, v in pairs(a) do
    print(k, v)
end

Would print:

    1       This
    2       is
    3       an
    4       Example
Ad
Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

No, k and v do not stand for a starting and ending value.



for loops take on two separate forms.

The simple incrementing:

for index = start, stop, stride do

and the generic iterator:

for values in expression do

The in makes a complete difference.


The thing to the right of the in, (e.g., pairs(tab)) describes a way to repeatedly get a list of variables (the things to the left, the k, v).

What pairs does is give out all of the keys and values (at that key) in a table. This is what k and v stand for.