Game Development Community

Short-circuit boolean evaluation

by Kevin James · in Torque Game Builder · 12/18/2012 (11:39 am) · 7 replies

Does TorqueScript do short-circuiting of boolean evaluations?

About the author

Computer security, digital forensics, and platform jumper enthusiast. shells.myw3b.net/~syreal/


#1
12/18/2012 (12:08 pm)
Unfortunately, no. I use a lot of nested if-statements because of that issue!
#2
12/18/2012 (12:16 pm)
Torquescript, just like C++ & Java has the typical short-circuit operators: that being &&, || (and, or). I'm fairly sure it operates the same as C++ as it reads left to right, top to bottom.
So...
$a = 0;
$b = 1;
$c = true;
$d = false;

if($a || $d)
  return false;
if($b || $c)
  return true;
if($a && $b)
  return false;
if($a && $d)
  return false; (because it's false!)
if(!$a && !$d)
  return true;

I think you get the point, if evaluation of statement is true, proceed with remainder, else return.

Not to confuse the issue, but only when it's 0 will it register as "not true", so any number or element registering as a non-zero can be true.
#3
12/18/2012 (4:29 pm)
Sure enough... TS has short-circuiting. I would *swear* on my grandmother's grave that I couldn't do this before:
// Type the following lines into the console:

==> if( $a && $a.foo() ) echo( "a" );
// Console prints nothing
// I remember it printing "Unable to find object: '' attempting to call function 'foo'"

==> $a = new ScriptObject();
==> function ScriptObject::foo() { echo( "b" ); return true; }
==> if( $a && $a.foo() ) echo( "a" );
// Console prints:
b
a

==> if( true && $a.foo() ) echo( "a" )
b
a

==> if( false && $a.foo() ) echo( "a" )
// Console prints nothing

On that first if-statement above, I remember that "$a.foo()" being called even if $a was equal to "". Either I had it remembered wrong or it got patched in one of the more recent 1.7.x releases.

Anywho! Thanks, Doc308, for making me take a look at this again.
#4
12/18/2012 (4:38 pm)
TorqueScript has had those operators for at least as long as I've been using the engines, if not before. TorqueScript hasn't really seen any additions to the operators over the years that I'm aware as all the standard ones are supported.
#5
12/18/2012 (8:25 pm)
Thank you fine people.

@Scott maybe the && operator has always been in TS, but was recently modified to reflect C++ more?
#6
12/19/2012 (9:32 am)
@Kevin
It hasn't been changed that I'm aware of, near as I can recall that's how it's been since TGE.
#7
12/19/2012 (10:24 am)
This is really funny to me. Many years ago I must have had an unrelated error. For 10 years I've assumed that TS evaluated all portions of a logic statement before combining the results. It was one of my biggest gripes that it didn't work like C! No more! Long live TS!