Stack overflow from loop

I’m trying to make a pipe generation script for my game however during the generation the script breaks from exhausting memory. I don’t understand why its doing it though.

The goal is to choose a pipe by chance

--The script
local function PickPipe()
local endResult = {}
for _, data in pairs(Settings.GenerationChance) do
	for c = 1, data.chance, 1 do
		table.insert(endResult,(data.Object))
    end
end

local chosenIndex = math.random(1, #endResult)
local chosen = endResult[chosenIndex]
return chosen
end

--The ModuleScript
local module = {
MaxNumberOfPipes = 50,
GenerationChance = {
	{
		Object = "StraightPipe",
		chance = 50,
	},
	{
		Object = "Four_Horiontal",
		chance = 25,
	},
	{
		Object = "Turn",
		chance = 25,
	},
}
}
return module

Have you tried adding a wait()?

I hadent thought I would need one. Its supposed to stop at a certain number but it ignores it.

Works fine for me, can you show the code that calls “PickPipe”?

local PipesNum = 0
local function SetPipe(Start,PipeType)
if PipesNum == Settings.MaxNumberOfPipes then return end
local Pipe = nil
if Pipes:FindFirstChild(PipeType) then
	Pipe = Pipes[PipeType]:Clone()
else 
	return false 
end

Pipe:SetPrimaryPartCFrame(Start)
Pipe.Parent = workspace
local FindNewStart = {}
for i,v in pairs(Pipe:GetChildren()) do
	if v.Name == "End" then
		SetPipe(v.CFrame,PickPipe())
		PipesNum = PipesNum + 1
	end
end
--local End = FindNewStart[math.random(1,#FindNewStart)]
--return End.CFrame
end

It may be a little messy, but I intend to clean it up once I get it working.

I believe this is the culprit. You need to increment the counter before you step into the recursion

1 Like

Okay, I think the issue is that you’re increasing “PipesNum” after calling the SetPipe function again. The SetPipe function just keeps getting called recursively inside of itself and the code never actually gets to the increment part. Try incrementing “PipesNum” before you call the SetPipes function again

PipesNum = PipesNum + 1
SetPipe(v.CFrame,PickPipe())
2 Likes

It works now. Thank you both for the help. This was my first time working with recursion.

1 Like