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

ipairs (t) help?

Asked by
NotSoNorm 777 Moderation Voter
10 years ago

I have been looking on the Wiki for a good definition of ipairs but I just don't understand. Can someone give me a good definition? Thanks

1 answer

Log in to vote
7
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago
Edited 7 years ago

ipairs is an iterator. This 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 of a list -- all of those that are counted in table length (#tab): 1, 2, 3, 4, ..., #tab

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

tab = {3,9,false,"a string",19}
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 (more or less) 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 "apples" in the above example)

0
Best explanation I have seen for pairs/ipairs yet. Good job : ) loak 7 — 7y
Ad

Answer this question