:connect
is not a straightforward use of functions -- it isn't using functions like they normally are.
This is a really good question -- this is a weird bit of code, and it's a little disappointing not many learning scripters realize how strange it looks.
I'm going to use the Touched
event as in my examples, but it works the same way as the MouseClick
event.
First, let's write our connection separately from the definition of the function:
1 | function makeRed( part ) |
2 | part.BrickColor = BrickColor.red() |
5 | workspace.Wall.Touched:connect( makeRed ) |
part
is defined, in the scope of the makeRed
function, to be the first value that makeRed
is given when called.
First of all, ignoring the :connect
line, we can just use makeRed
ourselves:
1 | makeRed(workspace.Player 1. Torso) |
2 | makeRed(workspace.BasePlate) |
The first line, part
will be the player's Torso; the second line, it will be the BasePlate.
Here's something Lua lets us do. It's called first class functions or higher ordered functions (EDIT: had serious nomenclature typo)
01 | function makeRed( part ) |
02 | part.BrickColor = BrickColor.red() |
05 | function makeBlue( part ) |
06 | part.BrickColor = BrickColor.blue() |
10 | if math.random( 2 ) = = 1 then |
20 | changer( workspace.BasePlate ) |
What happened here? changer
now stores the value of a function -- that means when we call changer
, it will actually be calling the function we assigned it to, which was either makeRed
or makeBlue
.
:connect
does a similar thing. When you say :connect( makeRed )
, you aren't calling makeRed
. You're giving the value of makeRed
so that ROBLOX can call it later.
Here's a fake implementation of how .Touched:connect( x )
might work:
1 | function connect( xfun ) |
3 | local near = getNearestPart( workspace.Wall ) |
4 | if areTouching(near, workspace.Wall) then |
How does it know what [the parameter's value] is?
Somewhere, :connect
is calling your function with a parameter -- :connect
tells your function what the parameter is, in the same way that functions normally get their parameters
Higher ordered functions are awesome. Here's an aside on the makeBlue
and makeRed
we had earlier:
01 | function makeColorChanger( str ) |
03 | part.BrickColor = BrickColor.new(str) |
07 | makeRed = makeColorChanger( "Bright red" ) |
08 | makeBlue = makeColorChange( "Bright blue" ) |
09 | makeGreen = makeColorChange( "Bright green" ) |
13 | makeRed( workspace.BasePlate ) |
15 | makeColorChanger( "Bright red" )(workspace.BasePlate) |
MouseClick Case
The parameter is the player who clicked. (It isn't the LocalPlayer -- a "Script" object (as opposed to a LocalScript) doesn't have the concept of a LocalPlayer)
ROBLOX obviously can know who clicked it, since the game has to know it was clicked at all (so it just also adds, "it was this guy"). So ROBLOX just informs the event of that information.