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

Am I using pcall correctly?

Asked by 4 years ago
Edited 4 years ago

I just recently came across someone using pcall and tried to implement it into my script so that no errors are produced, am I using this correctly?

script.Parent.Touched:connect(function(hit)
    pcall(function()
        humanoid = hit.Parent.Humanoid--this produced an error if it wasn't touching a player/humanoid, but its fine now that i put it in this pcall
    end)
    if humanoid then
        humanoid.Health = humanoid.Health - damage
    end
end)

This script works, but is there a way to improve it?

EDIT: i just realized I could use

local humanoid = hit.Parent:FindFirstChild("Humanoid")

instead, but could someone explain me to where i should use pcall

1 answer

Log in to vote
1
Answered by 4 years ago

Pretty sure it is, but a pcall's main usage is to catch any errors while running and inform the developer about it in the output. This is useful so that the code doesn't error and stop. This would be better to use:

script.Parent.Touched:connect(function(hit)
    local success, errorMesage = pcall(function()
        humanoid = hit.Parent.Humanoid
    end)

    if humanoid  then
        if success then
            humanoid.Health = humanoid.Health - damage
        else
            print("There was an error in the pcall.")
            warn(errorMessage)
        end
    end
end)
0
Ad

Answer this question