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

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

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?

1 comment

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.

1 answer

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.

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