Simplify if statement?

Is there a simpler way to do the following:

for i, v in placedAttachmentArray do 
	if v.Position == hingePreview.Position and previousHinge ~= nil then
		
		print("place hinge")
		print("place rod")
		return
		
	elseif v.Position == hingePreview.Position then
		
		print("place hinge")
		return
		
	end
end

Thanks!

for i, v in placedAttachmentArray do 
	if (v.Position-hingePreview.Position).Magnitude < 0.1 then -- Doing this so that if somehow the 2 positions are slightly different the code would still work.
		print("place hinge")
		if previousHinge ~= nil then
			print("place rod")
		end
		return
	end
end
2 Likes

For sure.

for _, v in placedAttachmentArray do
    if v.Position ~= hingePreview.Position then continue end
    print("place hinge")
    if not previousHinge then continue end
    print("place rod")
    return
end

yep, this is the solution. Can you tell me why you avoid having the print inside the if statements? Thanks!

These if statements are known as guard statements. Prints can be used in if statements, but in my preference, I use these to optimise my loops and functions.

Can you tell me how guard statements optimize the loops and functions? Thanks!

Like, I’m not sure how

if something == true then
    print("true")
end

is worse than

if something == true then
    continue
end
print("true")

Elseifs and nested ifs are sometimes slightly messy and with guard statements, it optimises the way you read it. Optimise is not always meant as boost performance.

1 Like

You ideally really only use it in functions and loops. Not in that case where you only check one thing.
Oh and continue is only used in loops, that second code would error.

Optimise is not always meant as boost performance.

hmmm, never heard of that, interesting
but thank you :smiley:

wow, the videos you sent really cleared that up. :smiley:

there are parts of my code that do look like 2:06 in the second video :joy:
I’ll clean that up immediately! Thank you!

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