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

Why does this script work if the function parameter is left undefined?

Asked by 6 years ago

Found it in chapter 3 of the scripting book, The script is placed inside a part and summons it to the players position constantly.

function onPlayerEntered(player)
    player.CharacterAdded:connect(function(char) --Anonymous function fired when player's character loads
        while wait() do -- Infinite loop!
            script.Parent.CFrame = CFrame.new(char.Torso.Position) -- Tele to player's position
        end
    end)
end

game.Players.PlayerAdded:connect(onPlayerEntered) -- connects function to PlayerAdded event.

What I don't understand is

function onPlayerEntered(player)
    player.CharacterAdded:connect(function(char)

Shouldn't player.CharacterAdded:connect(function(char) return nil since player isn't defined?

0
“player” would be defined though, as “player” is the player that joined the game. Plus you would be getting an error if “player” is nil. User#20279 0 — 6y

1 answer

Log in to vote
1
Answered by
Validark 1580 Snack Break Moderation Voter
6 years ago

game.Players.PlayerAdded:connect(onPlayerEntered) Connects onPlayerEntered to Players.PlayerAdded, which is an Event. That means it fires every time a player is added to the game.

In other words, when a player enters, the event triggers, and the function onPlayerEntered will be called with the parameter Player as can be seen on the wiki.

A Player is an object as well with its own events. One of these is called CharacterAdded, which fires whenever the Player spawns a new Character.

In short, the onPlayerEntered function fires whenever a player joins the game, and that function connects an event to the player's CharacterAdded Event. Once that fires, the inner anonymous function will be called with the parameter of the Player's Character.

Ad

Answer this question