Connecting events inside a for loop

So I was wondering if connecting events to every model within a folder via for loops is bad practice. I’m making a script for my game and I need the .Touched() event to be connected to numerous parts within a folder. The code for this is below. Is this bad for performance? Is it gonna cause memory leaks? Is it bad practice in general? Or is this not a problem at all?

local barrierFolder = game.Workspace:WaitForChild("BarriersFolder")

local function onFrontCollision(hit)
	print(hit.Parent.Name, "touched the front side of the barrier.")
end

local function onBackCollision(hit)
	print(hit.Parent.Name, "touched the back side of the barrier.")
end

for _, barrier in barrierFolder:GetChildren() do
	if barrier.Name == "Barrier" then
		local functionality = barrier:WaitForChild("Functionality")
		local frontPart = functionality:WaitForChild("Front")
		local backPart = functionality:WaitForChild("Back")
		
		frontPart.Touched:Connect(onFrontCollision)
		backPart.Touched:Connect(onBackCollision)
	end
end

The simple answer is: This works and is reasonable!

A more detailed answer

This is an example of functional programming, but object-oriented programming would probably help you make more reusable, efficient, expandable code. I would look into the concepts behind OOP if you want to learn something new. (:

Lua’s object-oriented features are kind of tacked-on to the language so they’re complicated compared to other languages but it’s something to experiment with.

2 Likes

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