What is the best loop to iterate through a container?

I understand this is an old frequent question, but I still find it confusing and am not exactly sure.
What is the different purposes and performance implications in every type of loop?

--Generic for i loop
for i = 1,#container do
    print(i,container[i])
end

--Generic loop
for index,value in container do
    print(index,value)
end

--pairs loop
for index,value in pairs(container) do
    print(index,value)
end

--ipairs loop
for index,value in ipairs(container) do
    print(index,value)
end

--table library functions
table.foreach(container, print)
table.foreachi(container, print)
2 Likes

Age old question, TL;DR: Use Ipairs for numerical arrays 1,2,3,…#table and pairs for dictionaries.

performance doesn’t matter in this case you won’t notice it so it’s negligible, also has the same conclusion TL;DR: Use Ipairs for numerical arrays 1,2,3,…#table and pairs for dictionaries.

Now this is the only interesting thing I found:

This is just a Luau shortcut for both ipairs and pairs.

The problem I see is backwards compatibility with Lua and also the fact that it’s vague readability and it doesn’t tell you if you are iterating through a dictionary or array, or both.

In Lua, to iterate over a table you need to use an iterator like next or a function that returns one like pairs or ipairs . In Luau, you can simply iterate over a table:

The default iteration order for tables is specified to be consecutive for elements 1..#t and unordered after that, visiting every element; similarly to iteration using pairs , modifying the table entries for keys other than the current one results in unspecified behavior.

1 Like

When it comes to performance I would say just ignore it but I believe Generic for i loop would be the fastest

Generic loop and pairs loop are both the same

Maybe this video might help explain the difference from ipairs and pairs

1 Like
for index, value in next, container do
	print(index, value)
end

Just to complete the list.

1 Like