Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can someone help me understand the concept behind for_, in pairs?

Asked by 5 years ago

I do not understand what for_, in pairs. Can someone help me?

2 answers

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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


iterators

generic for loops

generic for loops(2)

Hopefully this Helped!

0
yeah what you're basically saying is that the underscore character is just a variable name? right? DeceptiveCaster 3761 — 5y
0
yea its a dummy variable theking48989987 2147 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

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.

Answer this question