Using too many for "k, v in next, do" loops?

I have a bunch of for loops run when the game initializes, on the server and on the client.

This is on a server-sided module:

for i = 1, #things do
	local thing = things[i]
	...
end

However when I switch to using:

for i, thing in next, things do
	...
end

I get this error:
Script timeout: exhausted allowed execution time

Did I hit a limit to how many for loops using next?
I am using AeroGameFramework if that is any help.

1 Like

Could you expand on what the code in the loop is? I believe the problem might not be the loop header itself but you may have code within the loop mutating the loop state; this behavior seems consistent with that of an infinite next loop.

I am calling a function like so:

for i = 1, #things do
	local thing = things[i]
	func(thing)
end

The function I call varies. Sometimes I call a function from module script:

local function func(thing) --thing is an Instance
	module[thing.Name](thing)
end

--In another ModuleScript
local module = {
	["thing"] = function(thing)
		thing.Touched:Connect(function(hit)
		end)
	end,
}

Other times I am creating a new class:

local function func(thing) --thing is an Instance
	Class.new(thing)
end

I tested just 1 module in an empty place, it had the same error. So it is not using too many for loops that is the problem.

So what is the different between using a numeric for loop and a next for loop that could be causing the problem?

I uploaded a test place:
The ModuleScript is in ServerStorage.Aero.Services.ContraptionService, lines 44-51. The module script that is calls is in ServerStorage.Aero.Modules.ContraptionFunctions.
TestPlace.rbxl (72.0 KB)

The issue is that you cannot add keys to your table while iterating with next. The order of next is not defined and adding keys results in undefined behavior. It seems to be leading to an infinite loop in your case. Note that you can remove keys as you encounter them and next will handle it just fine. Adding keys is a big no-no though.

1 Like