- Home /
Shorthand for checking for multiple if's.....
Hi all. Really struggling to word this clearly, so apologies, and bear with me please! I often find myself checking for more than one state of a single variable, for instance
if(aNumber < 5 && aNumber > 1)
That isn't so bad, but with more complicated code it gets very long and sometimes complicated. Is there a way of expressing the "&&" to mean "the last expression again"? so something like
if(aNumber <5 ** >1)
Maybe nothing like this exists, but if it does I'd love to know! (this is in JavaScript btw).
Thanks
Ian
you can make a function CheckRange
function CheckRange(num : int, $$anonymous$$ : int, max : int)
{
if(num < max && num > $$anonymous$$)
return true;
else
return false;
}
and call it like
if(CheckRange(aNumber, 1, 5))
// Do ittt :)
you can create overloads for different types
but if this makes it more simple is a different thing ;)
InfiniBuzz - I didn't know that, so thanks, I've learnt something! It's not quite what I was after $$anonymous$$d, I was hoping there was an operator to mean "as well as" for the variable. Thanks anyway!
I know its not directly an answer ;) depending on what you are doing you could also create a more complicated check function that maybe returns an enum you can build a statemachine from (switch-case) - just brainstor$$anonymous$$g ;)
Ha, I don't need anything that complicated just yet, but I'll keep that in $$anonymous$$d. That checkrange function might come in handy actually. Cheers :-)
if(something)
return true;
else
return false;
can be written more simply/clearly as
return (something);
Also note that Unity already has a Clamp() method, though unlike yours, it is inclusive.
Answer by Owen-Reynolds · Jul 01, 2013 at 06:14 PM
No -- every compare needs both sides. But this is the standard slicing if from any good intro Computer Science textbook. This looks up the chart "-32:ice ; 32-211:water ; 212-999:steam ; 1000+ megasteam" using ifs:
if(t<32) g="ice";
else if(t<212) g="water"; // 32-211
else if(t<1000) g="steam"; // 212-1000
else g="megasteam";
The trick is general is to always work your way either up or down the range. Notice how each breakpoint (32, 212) is only listed once.
Answer by Eric5h5 · Jul 01, 2013 at 06:07 PM
Nothing like that exists. If your code is getting long and complicated, that usually suggests there's a better approach in general, rather than trying to use shortcuts (which make code difficult to read if they do exist).
Your answer

Follow this Question
Related Questions
If statement not working 3 Answers
Check if is destroyed 0 Answers
Overload Operator in UnityScript? 0 Answers
Is there a modulus operator in Unity JavaScript? 4 Answers
if ((this || that) && (that || this)).. Does that work? 3 Answers