Optimize these if statements

I feel a little stupid right now, as I can’t think of a way to optimize this code and reduce the Elseif statements. I’ve got a keypad puzzle that will reset if you mess up an input. The way it checks your progress is with an IntValue in the player. Here’s the code.

script.Parent.ClickDetector.MouseClick:Connect(function(plr)
	if plr.CodeProgress.Value == (3) then
		plr.CodeProgress.Value = (4)
		
	elseif plr.CodeProgress.Value > (4) then
		plr.CodeProgress.Value = (1)
		
	elseif plr.CodeProgress.Value < (4) then
		print("Four is greater than value")
		if plr.CodeProgress.Value ~= (3) then
			print("Value isn't 3")
			if plr.CodeProgress.Value > (0) then
				plr.CodeProgress.Value = (1)
				print("Value is not 0 so puzzle has been activated.")
			end
		end
	end
end)
script.Parent.ClickDetector.MouseClick:Connect(function(plr)
	if plr.CodeProgress.Value == (3) then
		plr.CodeProgress.Value = (4)
	elseif plr.CodeProgress.Value > (4) then
		plr.CodeProgress.Value = (1)
	elseif plr.CodeProgress.Value < (4) and plr.CodeProgress.Value > 0 then
		plr.CodeProgress.Value = (1)
	end
end)

Note that you’re not checking if the progress is 4.

Also, if you’re making something where player has to type a string perfectly, you can just store last inputs in a string and on each input check if last few characters are the correct result.

Seeing all of these magic numbers thrown around, I believe this is just a greater design issue. Could you explain what CodeProgress.Value being set to 2 or 3 might mean? Also, what is your base case? It seems that after 4 comes 1 but we never return to the uninitialized 0 case.

1 Like