What is the difference between pairs() vs. ipairs() in Lua?

In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table.

While both of them have some similarities, it is also good to know that they have some very notable differences that we should be aware of.

The first difference between the pairs() and ipairs() function is that the pairs() function doesn’t maintain the key order whereas the ipairs() function surely does.


Consider the example shown below −

 Live Demo

u["aa"] = "zz"
u[7] = "e"
for key,value in ipairs(u) do print(key,value) end
for key,value in pairs(u) do print(key,value) end

In the example above, the ipairs() function will print the order of the key in numeric order, whereas the pairs() function doesn’t guarantee it.

Also, if we look at the example a bit more closely, we will see the second difference, and that is that the ipairs() function doesn’t return non-numeric keys that are present in the table.


Consider the output for the reference.

1   a
2   c
3   b
4   d
1   a
2   c
3   b
4   d
7   e
aa zz