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

Which Touched event check is better?

Trying to make the check that will prevent the script from breaking when a bullet hits the brick.

script.Parent.Touched:connect(function(hit)
	if hit.Parent and hit.Parent:FindFirstChild("Humanoid") then
		hit.Parent.Humanoid.Health = 0
	end
end)
script.Parent.Touched:connect(function(hit)
	if hit.Parent then
		if hit.Parent:FindFirstChild("Humanoid") then
			hit.Parent.Humanoid.Health = 0
		end
	end
end)

I'm more inclined to use the first option, because it's cleaner, but I was worried that in the case hit.Parent doesn't exist, the part where it looks for a Humanoid would error because it assumes hit.Parent does exist. Therefore I'm not sure. Which one should I use? Please explain why I should use that particular option in your answers. Thanks.

3 answers

✓ Accepted answer

Neither is better in terms of the check. I would opt for the first because it's shorter and clearer -- fewer levels of indentation is almost always better (and the condition isn't long or unclear to accomplish it)


You're right to be suspicious about the first one, since after all, it looks like it checks both.

There's a bit of magic to how and works. Unlike most operations, it only evaluates what it needs to, starting at the left.

That means if the thing on the left is already false, it won't even bother checking the thing on the right (so the thing on the right is never executed to cause an error).

This is called short circuiting and it applies to or too (except that it stops if there's a truthy value instead). It's a form of lazy evaluation, and the only real such form in Lua.

2 comments

1

Ooohhhhh thanks a lot.

1

Lua's lazy evaluation of and and or is also the secret to the "ternary" operator: x = conditional and valueIfTrue or valueIfFalse

Use the first one as it is cleaner. It will work no matter what, if not then try this: Putting else will basically say if the object that has hit and does not have the Humanoid it will just end the script.

script.Parent.Touched:connect(function(hit)
    if hit.Parent and hit.Parent:FindFirstChild("Humanoid") then
        hit.Parent.Humanoid.Health = 0
           else
    end
end)

1 comment

1

Sorry but i already got an answer and putting else without any code after it is kinda pointless...

script.Parent.Touched:connect(function(hit)
	if(hit.Parent)and(game.Players:playerFromCharacter(hit.Parent))then
		hit.Parent.Humanoid.Health=0
	end
end)

2 comments

0

I'm telling you guys i already have an answer and thats not really explained at all...

0

Mine is better than the others...

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