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

Am I using pcall correctly?

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

✓ Accepted answer

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)

1 comment

0

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