Question regarding looping

So guys, I’ve seen that people use _, when looping in a for loop. Why is that? I’m confused.

Let’s take for an instance:

for _, player in pairs(game:GetService("Players"):GetPlayers()) do
       -- do stuff

What purpose does _, serve? Can someone explain it to me? Thanks in advance!

It depends, you can use i and v, but some people, whenever they don’t need the “i”, fill in it with an underscore. It’s completely preference-based.

1 Like

When you call different iterators, values are returned - ipairs for instance returns an iterator function, which itself returns the current index and value, you can store the index and value with any variable you want, people commonly use i, v in reference to the current index, value respectively.

The underscore (_) is a placeholder variable, people typically use it when they don’t require a certain value, for example when you need to traverse a dictionary but only need the keys:

 for k, _ in pairs(t) do end 
 -- note that you CAN use _ within the loop as a variable
ipairs in Lua
function iter (a, i)
  i = i + 1
  local v = a[i]
  if v then
    return i, v

function ipairs (a)
  return iter, a, 0

@SilentsReplacement you can use any letter (even a word) as a variable in a loop, to reference either the index or value.

 for index, value in pairs -- valid
 for _, value in ipairs -- valid
 for i, value in ipairs -- valid
 for i,v in pairs -- valid but often used incorrectly over ipairs

 for _, _ in pairs
 -- always, the _ will refer to the last defined variable as _ 
 -- in this loop, it (the underscore variable) will store the value - not key/index accessible within the scope of the loop