"Possible" stack overflow error

Hello, I am having a problem with my code

This is a research tree script (If you wish to see the full code, ask me although it’s not finished yet)

function createButton(id) <-- the function
	local research = tree[id]
	
	local button = buttonTemplate:Clone()
	local eraType = research.data.eraType
	
	-- the rest of the code that I don't wanna show much
	
	button.MouseButton1Click:Connect(function()
		local isResearched = commitResearch:InvokeServer(id)
		
		if not isResearched then
			return
		end
		
		for researchId, research in tree do
			if not table.find(research.requires, id) then
				continue
			end
			
			createButton(researchId) <-- the function from the above called inside the same exact function
		end
		
		button:Destroy()
	end)
end

I’m afraid this might cause a stack overflow error, but if it won’t then let me know!
Any possible way to get over this?

1 Like

Save your game, and then run it. You can see if it causes a stack overflow error.

You can go really deep before you hit a stack overflow. Thousands at least if I remember right. Is your research tree that long?

I think the only time I hit a stack overflow error was when I called a function, that called the function, and it accidentally looped itself.

It essentially was

local function createNametag()
     local nameTag = findNametag()
end

local function findNametag()
  if not nametag then
    createNametag()
  end
end

You can see the issue there…

Upon reading your code, I noticed you are using recursion inside an event. The event is linked to when the button is clicked. Since that is the only identifiable recursion I see, this is what should happen:

Every time you press the button, a loop will begin in tree and eventually a new button is created for however many items were in the tree. When those buttons are pressed, the cycle will continue.

The only minor problem with this is assuming you hit the maximum number of frames or stacks was it called before the script throws an error and stops working.

There shouldn’t really be a stack overflow and if you are too afraid, having a simple wait could help it act like a loop to prevent a probable stack overflow.

tl;dr if your tree is large, you might want to do something about that and just add a wait for safety, if there is an actual problem with the script, do state that since I don’t see an issue.

A function can’t read the variable inside a different function

You should make it like this

local nameTag

local function createNametag()
     nameTag = findNametag()
end

local function findNametag()
  if not nametag then
    createNametag()
  end
end
2 Likes

Yes, I’m well aware now, I was just giving the layout of what caused the error… Not the actual script. Thanks though. Lol.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.