Ad
Log in to vote
0

What is the difference between an ipairs loop and a pairs loop?

Asked by 24 days ago

The title pretty much sums it up. What is the difference between the two?

2 answers

Log in to vote
1
Answered by 24 days ago

The first difference between the pairs() and ipairs() function is that the pairs() function doesn't maintain the key order whereas the ipairs() function do. Also ipairs() are way faster than pairs()

ipairs is equivalent to a numerical loop, making it faster when iterating over large ordered arrays. pairs are used to iterate over tables that aren't arrays or are unordered

More info on these webs Devforum

Tutorialspoint

Devforum

Hope this helps!!

Ad
Log in to vote
1
Answered by
manith513 101
23 days ago
Edited 23 days ago

Here is an easy way to visualize it.

local table = {[5] = 5, [3] = 3, [4] = 4, [1] = 1, [2] = 2}

for i,v in pairs(table) do
    print(v)
end


--The above statement would print out 5,3,4,1,2

for i,v in ipairs(table) do
    print(v)
end

-- this would print 1,2,3,4,5 as it is doing it in order of the numerical indexes. 
0
in the pairs() one, the print is not accurate. pairs is actually in random order. so pairs would print either 53412; 25143; 34251; etc. T3_MasterGamer 1701 — 22d

Answer this question