Very long if statement

-- 		if Target.Parent ~= PlayerCharacter and Target.Parent:FindFirstChildOfClass("Humanoid") and not table.find(AlreadyHit, Target.Parent) and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("IsParrying") ~= true and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("Block") == false then

As we can see here, this if statement has a bunch of conditions. I was wondering if there’s a way to put all of the conditions into a table or just condense them into something smaller.

You can make the condition a variable

or

you can use if not then return

if Target.Parent == PlayerCharacter then
   return
end

if not (Target.Parent:FindFirstChildOfClass("Humanoid")) then
   return
end

-- blah blah blah

To make the if statement easier to read, you can scretch it to multiple lines, just like that:

if Target.Parent ~= PlayerCharacter and Target.Parent:FindFirstChildOfClass("Humanoid")
	and not table.find(AlreadyHit, Target.Parent) and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("IsParrying") ~= true
	and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("Block") == false then
	-- Do something
end

Edit: I have just realized that this is not something what you might want.

This is why I wouldn’t put a whole if statement in one line.

Write it like it’s supposed to be written:

if condition then
print("Doing stuff")
end
-- 		if Target.Parent ~= PlayerCharacter and Target.Parent:FindFirstChildOfClass("Humanoid") and not table.find(AlreadyHit, Target.Parent) and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("IsParrying") ~= true and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("Block") == false then

Can be:

local parent = Target.Parent
local Human = parent:FindFirstChildOfClass("Humanoid")
if parent ~= PlayerCharacter and Human and not table.find(AlreadyHit,parent) then
     if not Human:GetAttribute("IsParrying") and not Human:GetAttribute("Block") then
          -- do more stuff
     end
end

You could put it in a function

function condition(Target, PlayerCharacter, AlreadyHit): boolean
    return Target.Parent ~= PlayerCharacter and Target.Parent:FindFirstChildOfClass("Humanoid") and not table.find(AlreadyHit, Target.Parent) and Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("IsParrying") ~= true and not Target.Parent:FindFirstChildOfClass("Humanoid"):GetAttribute("Block") and true or false
end

if condition(Target, PlayerCharacter, AlreadyHit) then
    -- stuff here
end

Also don’t lengthify the return I suggest you to use @JustOneFreshAccount’s solution.

function condition(...): boolean
    if not ... then
        return false
    end

    -- ...
    return true
end
1 Like

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