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.
1 | a = { "This" , "is" , "an" , "Example" } |
2 |
3 | for k,v in pairs (a) do |
4 |
5 | print (v) |
6 |
7 | 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?
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,
1 | local t = { name = "emite1000" } |
2 | -- 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).
1 | for _, v in pairs (Players:GetPlayers()) do |
2 | v:Kick() -- in this example, only the value is used. |
3 | 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:
1 | a = { [ 1 ] = "This" , [ 2 ] = "is" , [ 3 ] = "an" , [ 4 ] = "Example" } |
Which means, printing the key and value like so...
1 | for k, v in pairs (a) do |
2 | print (k, v) |
3 | end |
Would print:
1 | 1 This |
2 | 2 is |
3 | 3 an |
4 | 4 Example |
No, k
and v
do not stand for a starting and ending value.
for
loops take on two separate forms.
The simple incrementing:
1 | for index = start, stop, stride do |
and the generic iterator:
1 | 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.
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?