Will a repeated Connect() function for the same object create some stack overflow?

I have a function that is called many times from different places and inside this function, I have this Connect, for example:

function MyFunction()
    Button1.MouseEnter:Connect(function()
        --- any script
    end)
end

 MyFunction() -- 1st time
 MyFunction() -- 2nd time
 MyFunction() -- 3rd time

I worry that this repetition (Button1.MouseEnter:Connect called 3 times) will cause some stack accumulation?

2 Likes

if you call the function three times, it would run three times as much as before

I wouldn’t do this

2 Likes

It can cause stack accumulation.
Just avoid creating connections if unnecessary, or if one is already created.

1 Like

‘Can’ or ‘Will’ cause stack accumulation?
Is there a way to confirm this?

1 Like

I don’t have an answer to whether it Will or not.
You can maybe use debounces to avoid that.
Edit: The more calls there are, the more likely it is to occur. Even if the impact will not be visible,
consider the performance cost.

1 Like

just :Disconnect() connections you don’t use

2 Likes

@D0RYU
Sorry, but I think Roblox Lua is an exact science. Either it is or it isn’t, so there is no room for ‘maybe’.
So I ask how can I confirm whether there will be an accumulation or not in this case and how to test and prove it?

2 Likes

Try calling the function on a certain rate, and check for a visible impact.

1 Like

why do you need this in your game anyways?
if you call it three times you should be fine, I don’t recommend it though

2 Likes

I am not an expert on the internals of the Luau compiler or runtime but I believe it would cause Stack Accumulation because each time MyFunction is called it is going to create a new copy of the anonymous function you connect and put that on the stack.

However Stack Accumulation is not the same as Stack Overflow. Will MyFunction cause a stack overflow with only three calls, not unless the code in the anonymous functions does something to cause the overflow.

The code sample provided is inneficient and wasting memory, if you really need to do what it does at least move the anonymous function to a named local function, so that only one instance of the function exists.

Stack overflows frequently happen when you create an infinite loop or execute an unbounded recursive action. Most runtimes have limits on how deep a recursion is allowed to go before throwing a stack overflow error often 32 levels (not sure about Lua).

2 Likes