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

Whats the difference between putting multiple if statements and multiple elseif statement?s

for i,v in pairs(game.Workspace:GetChildren()) do
	if v:IsA('Tool') then
		
	end
	
	if v:IsA('Part') then
		
	end
end


for i,v in pairs(game.Workspace:GetChildren()) do
	if v:IsA('Tool') then
		
	elseif v:IsA('Part') then
		
		
	end
	
	
end

Does anyone know what difference this makes and what I should use?

2 answers

Here's a comparison

for i,v in pairs(game.Workspace:GetChildren()) do
    if v:IsA('Tool') then --//v:IsA("Tool") == true; execute code
		
    end

    if v:IsA('Part') then --//v:IsA("Part") == true; execute code
		
    end
end

--//Is not the same as:

for i,v in pairs(game.Workspace:GetChildren()) do
    if v:IsA('Tool') then --//v:IsA("Tool") == true; execute code
		
    elseif v:IsA('Part') then --//v:IsA("Tool") == false, and v:IsA("Part") == true; execute code
		
    end
end

Logic wise these aren't the same thing. A more apt comparison would be

for i,v in pairs(game.Workspace:GetChildren()) do
    if v:IsA('Tool') then --//v:IsA("Tool") == true; execute code
		
    elseif v:IsA('Part') then --//v:IsA("Tool") == false, and v:IsA("Part") == true; execute code
		
    end
end

--//Is the same as:

for i,v in pairs(game.Workspace:GetChildren()) do
    if v:IsA('Tool') then --//v:IsA("Tool") == true; execute code
		
    end

    if not v:IsA('Tool') and v:IsA('Part') then --//v:IsA("Tool") == false, and v:IsA("Part") == true; execute code
		
    end
end

In this one you could just use an elseif instead of two if statements since they do the same thing logic wise.

Just depends on what you need them for but you can make do without an elseif if you really wanted to, but at the cost of a bit of organization within your code.

2 comments

1

A thing to note, elseif statements are very important in some codes that are very variable reliant as otherwise you may run into the issue of an unintended if statement running because a previous one set the variable to what the next required before the if statement runs, thus causing the next one to run even if it wasn't supposed to.

1

Without elseif statements, it could make each subsequent if statement more complicated if you have multiple if statements working on one variable, so while it's possible it's not practical.

Elseif makes your code look nicer and you don’t have to put multiple ends.

1 comment

0

Sorta true, but not quite. It also makes less comparisons. If you use all if's, then we would be running all the if statements. If we did if/elseif/elseif it would go down the code until it finds the if statement that is true and then doesnt run the rest of the if statements

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