Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How does the (function() work? And how do parameters work?

Asked by 6 years ago

I understand how doing functions like: function dog(). But many people seem to be doing it like: (function(x). Can someone explain to me how to use it that way. Also how do parameters work?

1 answer

Log in to vote
0
Answered by 6 years ago

I'll assume you ment something like this:

thing.SomethingHappened:Connect(function(x)
    -- do something
end)

I will try to explain this step by step. First, thing. This one is quite simple - thing is any instance. For example, it could be a model. I changed the code above a bit to make it easier to understand. I'll explain later:

thing.SomethingHappened:Connect()

Next, SomethingHappened. As the name I used here suggests, that's an event. This event is fired when something happens to thing. Note that SomethingHappened is not the name of a real event, so let's change it to ChildAdded - a real event that occurs when you add a child to an instance - for example, drop a part into a model in the explorer:

thing.ChildAdded:Connect()

Then there's :Connect. It's a method of the ChildAdded event (note: every event has this method). You can pass it a function as an argument - myFunction, in this case, which was declared somewhere else in the script. When the ChildAdded event is fired, it will pass all the info (in this case, the child that's been added) to myFunction as arguments and run it:

thing.ChildAdded:Connect(myFunction)

Finally, onto the part that you don't understand... If I've explained everything well, then you know that this (function(x) end) inside the :Connect at the beginning of my post, is the function that will be fired when the SomethingHappened event is fired by thing. What I'm doing here, is instead of passing a function that's already declared somewhere else, I'm declaring the function inside the :Connect, without a name, and instantly passing it:

thing.ChildAdded:Connect(function(child)

end)

Here's a working example of how you can use this. Remember to set the thing variable first!

thing.ChildAdded:Connect(function(child)
    print(child.Name.." was put into "..thing.Name.."!")
end)
Ad

Answer this question