Which is better?
by James Thompson · in Torque Game Engine · 07/29/2006 (5:17 am) · 3 replies
Im trying to figure out why/when
Which of these is better and why?
1.
2.
3.
Thanks In advance
elseis needed
Which of these is better and why?
1.
// DRL stuff
if($pref::DRLOn $="0"){
DRL(false);
echo("DRL is turned off");
}else{
if($pref::DRLOn $="1"){
setdrl();
} else{
if($pref::DRLOn $="2"){
setdrl();
optimizeDRL(true);
}
}
}2.
// DRL stuff
if($pref::DRLOn $="0"){
DRL(false);
echo("DRL is turned off");
}else{
if($pref::DRLOn $="1"){
setdrl();
}
}else{
if($pref::DRLOn $="2"){
setdrl();
optimizeDRL(true);
}
}3.
// DRL stuff
if($pref::DRLOn $="0"){
DRL(false);
echo("DRL is turned off");
}
if($pref::DRLOn $="1"){
setdrl();
}
if($pref::DRLOn $="2"){
setdrl();
optimizeDRL(true);
}Thanks In advance
About the author
Been a programmer for a few years, started when I was quite young and got into it so carried on through my life. Currently studying at Kent Uni in Canterbury.
#2
If $pref::DRLon is really assgined as an int eg $Pref::DRLon = 1; rather than $Pref::DRLon = "1"; then you can use.
I havn't tested this, but you may be able to assign as "1" and still compare as an int, since script is typeless. However if you assigned "on" or "off" as the variable then you must use the above "switch$" for string evalution.
If you really wanted to stick to ifs then I'd use a varient on your third example, instead of three seperate ifs you would use two else ifs. This helps avoid evaluating the 2nd and 3rd "ifs" when the first if evaluates to true.
07/29/2006 (6:01 am)
In this case because you're simply selecting between different code based on a single variable I'd favour using "switch". In script you can use "switch" on numeric values or "switch$" for strings.switch$( $pref::DRLon )
{
case "0":
DRL(false);
case "1":
setdrl();
case "2":
setdrl();
optimizeDRL(true);
}If $pref::DRLon is really assgined as an int eg $Pref::DRLon = 1; rather than $Pref::DRLon = "1"; then you can use.
switch( $pref::DRLon )
{
case 0:
DRL(false);
case 1:
setdrl();
case 2:
setdrl();
optimizeDRL(true);
}I havn't tested this, but you may be able to assign as "1" and still compare as an int, since script is typeless. However if you assigned "on" or "off" as the variable then you must use the above "switch$" for string evalution.
If you really wanted to stick to ifs then I'd use a varient on your third example, instead of three seperate ifs you would use two else ifs. This helps avoid evaluating the 2nd and 3rd "ifs" when the first if evaluates to true.
// DRL stuff
if($pref::DRLOn $="0")
{
DRL(false);
echo("DRL is turned off");
}
else if($pref::DRLOn $="1")
setdrl();
else if($pref::DRLOn $="2")
{
setdrl();
optimizeDRL(true);
}
else
error("pref::DRLOn unhandled value:" SPC $pref::DRLon SPC "in whateverthisfunctionis");
#3
07/29/2006 (6:03 am)
Thanks Gary, I've never used switches, didnt understand them, I do now though, Thanks for your help
Torque Owner James Thompson
Keiouu Studios