Does for in pairs refresh?

I just wanted to know whether if an array is updated, would the for in pairs loop recognize the change, or would I have to run it over again?

It is important that I know this for a script I am creating.

1 Like

I believe so, I just tested a pairs loop that inserts new values into it when it runs and my studio crashed

Edit: Yes, it does refresh

1 Like

Depends where a new value is added and how you are traversing the table.

It does if you add the value ahead of the loop’s current index, but realistically you would either need to have a wait in your loop or a table so long that looping through it would pose performance concerns regardless of whether it works - both are unideal.

Repro:

local tbl = {1,2,3,4,5,6}
coroutine.wrap(function()
	for i,v in pairs(tbl) do
		print(i,v)
		wait()
	end
end)()
table.insert(tbl,7,7)
1 Like

This is likely reliable for ipairs and a pure-array table (when nothing in the loop yields), but the order that regular pairs iterates dictionary keys is not so well defined, so it would be unwise to write code that modifies a dictionary while iterating it.

It’s just generally safer and the better practice to take a second pass over the arrray.

1 Like

Agreed, though speaking on the “pure-array” statement, the insertion would have to be exclusively in-front of the present iteration’s index for even that to be reliable - anything behind and it will inherently disrupt the iterator causing both indexes, and values to repeat themselves.

Either way, I certainly concur that it is more reliable and an over-all better alternative to just run through the table a second time.

1 Like