Number of iterations changing during the iteration itself

I have come across an incident where the loop is changing the number of iterations during the iteration itself when I add more keys into the table as you can see below. In my case, I had to replicate this table into a temporary table to use for iteration and update the existing table to avoid this conflict. This feels odd to me and I have been wondering whether it’s normal behavior or whether I have missed out on any recent update… What are your thoughts?

Output:
image

Code:

--Table
local tbl = {
	["Apples"] = 1,
	["Oranges"] = 2
}

print("-----------------------------------------------")

--Loop 1
local count1 = 0
for i,v in pairs(tbl) do
	print(i,v)
	count1 += 1
end
print("Iterations from loop 1 :: " .. count1)

print("-----------------------------------------------")

--Loop 2
local count2 = 0
for i,v in pairs(tbl) do
	print(i,v)
	tbl[v] = i
	count2 += 1
end
print("Iterations from loop 2 :: " .. count2)

print("-----------------------------------------------")
1 Like

Whenever you add new keys to a table while it’s being iterated through, the new keys will affect the loop as shown in your case, and vice versa with removing keys.

1 Like