Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I use the DRY principle on this block of code?

Hey all, Merry Christmas to those of you that celebrate it. I'm writing a chunky code, and I have a single function that 4 events will trigger. Each of these 4 events takes up a line of code, which eventually adds up later. How would I enforce DRY (Don't Repeat Yourself) on such a block?

local function Click()
print("Do Stuff")
end
Button1.Activated:Connect(Click)
Button2.Activated:Connect(Click)
Button3.Activated:Connect(Click)
Button4.Activated:Connect(Click)

1 comment

0

Are Buttons Tools?

1 answer

I can clearly see that you're using the wrong event/trigger. This is a UI object, am I right? If so, the click is detected by doing MouseButton1Click.

local function Click()
	print("Do Stuff")
end
Button1.MouseButton1Click:Connect(Click)
Button2.MouseButton1Click:Connect(Click)
Button3.MouseButton1Click:Connect(Click)
Button4.MouseButton1Click:Connect(Click)

Also, please make sure that Button1, Button2, etc are variables, if they are not, you can declare a variable by doing this:

local Button1 = script.Parent

1 comment

0

Activated is an event of GuiObject, which will fire once the UserInputState is ended. https://developer.roblox.com/en-us/api-reference/event/GuiButton/Activated This block of code is at the bottom of my script, after defining all the variables. There's nothing wrong with my script, I'm simply asking if there's a way to shorten this chunk.

This discussion is preserved as it was. New answers, comments, and votes are closed.