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?
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.
@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?
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).