Time to time, I see in for loops something like for _,v in pairs (table) do
and I have no idea what it means. I understand that these are just defining a variable but what does the underscore mean? How is it different from i,v
? If you can, can you also please tell me why most people use
for i =
in for loops? Help is greatly greatly appreciated. Thank you.
The character itself doesn’t have much significance, it just simply represents an ignorance figure—a blank space. Even though it still is supplied with the identical index data, we still use it a form to conventionally signify that the parameter is insignificant to actions we’re performing inside the iteration function.
Here is a example to help put the information above into perspective:
local arbitraryTable = {1,5,true,"Hello!", nil} for index, value in pairs(arbitraryTable) do print(index, value) end --[[ Output: 1 1 2 5 3 true 4 Hello 5 nil ]]
In that code, we wanted to use the current index (where were are in the table) and it’s affiliated element. But let’s say we didn’t want to use that index, we signify that like so:
local arbitraryTable = {1,5,true,"Hello!", nil} for _, value in pairs(arbitraryTable) do print(value) --[[ We mark that we don’t want i, and as you see it isn’t used at all.]] --[[ print(_) If you run this, you’ll see _ still contains the information anyway]] end --[[ Output: 1 5 true Hello nil ]]
This can be done vice-versa, as it really doesn’t matter how you use _
. Like I said, it’s not significant to the language at all, so technically wherever we don’t want to use a space, we fill it with “nothing” by using _
. You can write for i,_ in pairs(table) do
for all that matters.
As for for i =
, this is identical to the behaviour as i,v
, it simply provides us with a variable local to the function scope that contains information that is determined by the function itself. In this case, i
will represent a # based on the iteration principles given: start, stop, skip
:
for i = 1,5 do --// *start* at 1, go to 5 *stop at* print(i) end --[[ Output: 1 2 3 4 5 ]] for i = 0,10,2 do --// Skip by 2 print(i) end --[[ Output: 0 2 4 6 8 10 ]]
They are the same. However, you cannot read the value of the index if you set the name to _
.
No Difference, the first variable is the Index and the second one is the Value. All the following ones work:
For i, v in pairs For ind, var in pairs For i, player in pairs
Etc