Elseif elseif elseif elseif elseif elseif

Does anyone know how to optimize the common “elseif” problem?

People say that repeating an elseif statement in an if statement makes it go harder to work and causes optimization problems in the long run. I believe it’s true and that there are better ways to make the same procedure. The thing is I don’t know how. I’ve read about it an it stated that you would need to use maps, but maps aren’t (by itself) a thing in roblox, maybe the closest there is to it is tables, and if it’s not tables is metatables. And I don’t know anything about metatables.

So, my question is, how would you make a better code without saying elseif continuously…?

This is an example:
 game["Run Service"].RenderStepped:Connect(function()
	camera.CFrame = camera.CFrame * CFrame.new(currentx, currenty, 0)
	principalcoord.Position = principalcoord.Position + Vector3.new(currentx, 0, currenty * -1)
	
      if camera.CFrame.X >= 85.025 or camera.CFrame.Z >= 180.998 or camera.CFrame.X <= -132.96 or camera.CFrame.Z <= -201.975 then
	   camera.CFrame = CFrame.new(0,220,0) * CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0)
	   principalcoord.Position = workspace.PrincipalCoord.Position
      end
end)

mouse.KeyDown:Connect(function(key)
	if key == "w" then
		currenty = .5
	elseif key == "a" then
		currentx = -.5
	elseif key == "s" then
		currenty = -.5
	elseif key == "d" then
		currentx = .5
	end
end)

mouse.KeyUp:Connect(function(key)
	if key == "w" then
		currenty = 0
	elseif key == "a" then
		currentx = 0
	elseif key == "s" then
		currenty = 0
	elseif key == "d" then
		currentx = 0
	end
end)

mouse.Button1Down:Connect(function()
	local piecepos = principalcoord.Position
	principalcoord:Destroy()
	pieceposevent:FireServer(currentpiece, piecepos)
	script:Destroy()
end)

By the way, yes, I want to optimize that part, but I also want other people to know how to optimize it if they have a similar code…

7 Likes

elseif chains like the ones you show aren’t really a problem. That seems like a perfectly reasonable way to use it. The issue is when you have upwards of say 6 or 7 different conditions, or a few conditions with a lot of code.

In the case of really big logic blocks, you can probably just contain the body of your if inside a function and just call that instead.

If you are having issues with many many branches, the alternative is also storing the code in functions. The functions would be put into a table by some key which your if might’ve used to compare. In this case, you can rewrite it to just do branches_table[key](any_additional_info).

11 Likes