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

What does this mean?(pairs function)

Asked by 10 years ago

I'm new at scripting and I've checked the wiki but I do not understand what this means:

for i,v in pairs(t) do

If you could let me know I would be very grateful, thanks!

1 answer

Log in to vote
0
Answered by
NotSoNorm 777 Moderation Voter
10 years ago

ipairs is an iterator. This basically means that it's a function which can be used to traverse objects in a for loop.

ipairs is used like this:

for index,value in ipairs(tab) do

    print("tab[",index,"] is ",value);

end

ipairs traverses all of the indices that are counted in table length (#tab), which is the consecutive positive integers beginning at one.

For the above stated loop, and the following value of tab,

tab = {3,9,false,"a string",19,nil,18};
tab.apples = "17";

this would be the output:

tab[    1   ] is    3

tab[    2   ] is    9

tab[    3   ] is    false

tab[    4   ] is    a string

tab[    5   ] is    19

In fact, an ipairs loop is equivalent to this:

for index = 1,#tab do
    local value = tab[index];
  -- Do whatever else in loop

end

Hopefully this explains things.

ipairs can be contrasted to pairs in that pairs traverses all indices, not only the consecutive whole numbers (hence we would have an extra entry for indices 7 and "apples" from the above example)

[P.S. This is not my explaining of it. This is Blues]

Ad

Answer this question