"local function ... (player)" does not work correctly

The “print” code in this script gives “nil”, what could be the cause of the problem?

local function part(player)
    print(player)
end

game.Players.PlayerAdded:Connect(part())

also when I type “player.Name” instead of “player” it outputs ““Connection attempt failed: Value passed is not a function””.

local function part(player)
    print(player.Name)
end

game.Players.PlayerAdded:Connect(part())

remove the () from inside the Connect

how to use it in this way because I’m getting “nil” output again

local function part(player)
    print(player)
end

while wait() do
    part()
end

you’re not passing on a player, you’re simply sending a function nothing.

local function part(player)
    print(player)
end

while task.wait() do
    part(game.Players.HayriPatir2)
end

also, wait() is deprecated, meaning it is not supported. switch it to task.wait()

1 Like

What is the difference between task.wait and wait

as I said, wait() is deprecated. meaning roblox no longer supports it. task.wait() is better and is supported and helps with performance

As @CZXPEK said, you need to use without () to pass a function, not run it

local function part(player)
    print(player)
end

game.Players.PlayerAdded:Connect(part)

The reason why nil is printed is because the part function is being called inside of the connect function and nothing is being passed which means nil is being printed. PlayerAdded is also never connected because a function must be passed into connect().

You can fix your code by removing () in the connect function in the last line so that it looks like this

game.Players.PlayerAdded:Connect(part)

A little off topic but I thought I might as well put it here. You should probably account for cases where PlayerAdded is connected after a player has joined resulting in PlayerAdded never firing for that player. This can be caused by many things like having yielding code above where you connect PlayerAdded or your script not starting immediately.

The code below shows a loop being ran after connecting the PlayerAdded to catch any players that might have joined the game after the PlayerAdded function was connected.

local Players = game:GetService("Players")

local function onPlayerAdded(player)
	print(player)
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetChildren() do
	task.spawn(onPlayerAdded, player)
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.