Loops vs copy/paste code

Hello! I just became a member recently so I apologize if I get anything wrong. Anyway…

I don’t know a way to word this correctly but heres an example.

I created 2 buttons that do the exact same animation with two ways I can run them. Which one is the better way to do for optimization/performance?

local Table = {a,b}

Method 1:
f(x) =
for i,v in ipairs(Table) do
v.InputBegan:Connect(function()
v.BackgroundTransparency = 1
end)
end
end

Method 2:
1f(x) =
Table[1].InputBegan:Connect(function()
Table[1].BackgroundTransparency = 1
end)
end

2f(x) =
Table[2].InputBegan:Connect(function()
Table[2].BackgroundTransparency = 1
end)
end

You really shouldn’t worry about stuff like this when the loop is only ever going to run once at the start of the game.

Well no the loop will run if a player clicks on either button. So it’s running when they choose to run it

They both do the same thing its just i’m copying and pasting on Method2 which takes up more space

I think you’ve got the wrong idea. This is what’s happening:

  • The loop runs a single time and registers event listeners for every GuiObject in the table.
  • When you hover over the GuiObject, the function you registered in the loop is called; it doesn’t loop over all of the elements again.

It would be better to use the loop since it scales well with your game whereas manually copying and pasting wouldn’t scale if you were to add more items.

1 Like

Oh I see! I thought the loop was actually constantly running… I’ll mark this as an answer. Thanks!

Why would you need the loop to run constantly when the Input Began event is already connected to all UI elements in table at beginning?

I don’t need it to run constantly I just thought that for loops looped the entire table not once

Next time do write code with 3 back ticks ``` on the top of your code to make it into code font :slight_smile:

I just learned this aswell so thought I’d share this out to other new members of the forum

1 Like

When I said this I meant it goes through the entire table a single time, sorry if it was confusing.

i’ll make sure to do it next time I post…

1 Like

Oh, so you might want to have a refresh through the loops documentation and how they work. Just saying so you don’t have any more doubts and are clear what what different loops do :slight_smile:

1 Like

completely alright! at least I now know that the first method is more efficient then the 2nd