how to prevent putting events in loops

  • for example:

    for i, v in pairs(parent:GetChildren()) do
            -- code is written here but it’s the same exact thing 

    That is really bad practice. Mainly because the script will run the same exact code when a property changes or you make your code ridiculously long because you want different code to run when a specific object is changed and use if statements to check for this.

    Instead, make a separate script with Disabled set to true and set it to false once cloned into the object.

        -- Code here

    Now that you’ve avoided bad practices, let’s clone this bad boy.

    for i, v in pairs(parent:GetChildren()) do
        local sc = script.ChangeScript:Clone()
        sc.Parent = v -- set parent first, then enable it 
        sc.Disabled = false 
        -- script must’ve manually been set disabled to true from explorer. set disabled to false so code runs

  • @incapaz Events in loops aren't bad, though. What if you want the same functionality for everything? Also, turning things disabled and enabled seems like it would cause a mess, disabling the wrong thing, enabling the wrong thing, etc. Just parent the script to the part in the first place!

  • @hiimgoodpack You can’t enable/disable the wrong thing. It’s just not possible. You access the script in mine like this:


    I doubt you can get it wrong. Someone who gets that wrong is mentally unstable.

  • Global Moderator

    Ew, ew, no, don't do that. You shouldn't ever have to manipulate scripts programmatically in your games. It's just bad game design. Long gone are the days of cloning and enabling/disabling scripts in Roblox.

    As hiim pointed out, making event connections in a loop is perfectly fine. It can be a very powerful construct when used correctly. However it would be better to define the function outside the loop and re-use that same function instead of inside the loop, which would cause the creation of several different closures.

    Of course this isn't always possible (if the function makes use of upvalues that depend on the current loop iteration), and in those cases it's perfectly fine to define the function inside the loop, but consider defining it outside if possible.

Log in to reply

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.