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
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)