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:
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("-----------------------------------------------")