I do not understand what for_, in pairs. Can someone help me?
Can someone help me understand the concept behind for_, in pairs?
2 answers
I'm assuming that you are trying to describe a generic for loop here.
Generic For Loops
Generic for loops are one of two types of for loops in lua. the first being numeric for loops, which are formatted like such:
for iterator = start,finish,increment do
...
end
Well, Generic for loops are formatted like:
for key,value in pairs(table) do
...
end
Generic for loops can also be formatted like:
for substring in String:gmatch(pattern) do
...
end
There are three iterators that can be used when constructing a generic for loop,
pairs, ipairs, and next. Ipairs being best for arrays, and pairs and next being best for dictionaries.
Each time an iterator function is called, it will return the "next" value from a collection
References
Hopefully this Helped!
Extension to theking48989986's answer
His answer is explained very well but I assume you want to know what the _ means.
The underscore (_) character isn't anything special in Lua; people use it as a placeholder. Say you had a function that returned two values, but in the situation you're in, only the second return value is necessary.
local function fn()
return {}, 8
end
local tbl, num = fn()
You can't just skip tbl and put local num or else num is a reference to the table. It doesn't hurt to still have your tbl variable but you don't need it. So people use an underscore to show they don't care about a value.
local _, num = fn()
print(_) -- it still works as a variable! (not encouraging you do this for important ones)
So people use _ in generic for loops to show they don't care about the index but are still required to fill it in so the codes are valid.
for _, v in pairs(tbl) do
...
end
-- No difference!
for i, v in pairs(tbl) do
...
end
It's just visual preference.
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
yeah what you're basically saying is that the underscore character is just a variable name? right?
yea its a dummy variable