Ipairs, pairs usage

When using ipairs and pairs for iterating over a dictionary, is there a difference when not using either?
for example:

local dictionary = {
	["a"] = 1,
	["b"] = 2,
	["c"] = 3
} 
for key, value in dictionary do
       ...
end

This code snippet iterates over a dictionary without the use of ipairs. Is there a difference in the usage of ipairs and not using it?

1 Like

In this instance, doing key, value in pairs(dictionary) is the same as key, value in dictionary, while ipairs would not loop over it at all since it’s not an array-like table.

I’m not entirely sure about the underlying implementations of pairs/ipairs but in case this is relevant, iterating over a table directly will call the underlying metamethod __iter if it does exist, while pairs and ipairs will not. You can see an example of this in a similar thread I talked about this in.

2 Likes

In Lua, arrays are implemented as tables with consecutive integer keys starting from 1. When you use the ipairs iterator, it specifically iterates over the numerical indices of the table in ascending order. This guarantees that the elements of the array will be traversed in the order they appear in the table.

local dictionary = {
	[1] = "Banana",
	[2] = "Apple",
	[3] = "Mango"
}

Using ipairs to iterate over this loop will always go in the order Banana, Apple, Mango. However if you used pairs to iterate over this dictionary the right order is not guaranteed, which could output the order Mango, Banana, Apple.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.