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
end
end
function ipairs (a)
return iter, a, 0
end
@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