How do I use Pcalls() ? and do you need to use pcall() in: “for i, player in pairs(Players:GetPlayers())”

do you need to use pcall() in: “for i, player in pairs(Players:GetPlayers())”

I’m attempting to make every second, it loops through the players and makes changes to a random body part,
<<<<<<<<<<<<<<<<<<

I’m worried about getting an error when trying to reference a player that left the game and no longer exists.
I remember reading about pcall() to protect the script from errors, I was wondering if this is an issue I need to worry about

How pcall() how

And my question on Pcall() is how do I use this?

From what I understand you first make local variables like this

 local SuccessYesOrNo, ErrorMessage = pcall()

but what I don’t understand is what I put inside the parenthesis and how to format it.

You could simply check if their character is part of the workspace and choose another player if it isn’t.

but what happens if this happens

  1. check if the character is in the workspace → true
  2. player leaves
  3. character.Arm.color = (1,1,1) → error becuase character doesnt exists anymore

The way Roblox Lua works is such that if it exists it won’t suddenly not exist while you still have reference to it, and especially not if you don’t yield at all in that block - your entire code up until the next yield will run before their parts get removed.

for _, player in ipairs( game.Players:GetPlayers() ) do
    if player.Character and player.Character:IsDescendantOf( game.Workspace ) then
        local arm = player.Character:FindFirstChild( 'Arm' )
        if arm then
            arm.Color = Color3.new()
        end
    end
end

That entire block will run non-stop without any yielding. If a player left in the middle of that loop, it would not break as nothing would be removed from the game until that block had finished. It’s just the way the task scheduler runs. Each “thread” in RBXLua will run until it yields, then essentially hand over processing control to the next thread that’s waiting.

4 Likes

That would be highly unlikely as scripts run so fast, make sure you don’t have waits. Additionally you could check if the part you want to change exists before changing it.

Unless you use a wait somewhere I sincerely doubt the person can EVER leave within the time frame of the code being executed. But here is an example on how pcalls work.

local Success, ReturnedValue = pcall(function()

return "test"

end)

if not Success then -- CODE ERRORED

print(ReturnedValue) -- Prints the error

else

print(ReturnedValue) -- This prints "test

end
3 Likes

this is super helpful thanks

(30 charsss)