Floating point as bool
by Nathan Jansen · in Torsion · 08/31/2009 (6:22 pm) · 1 replies
%float = 0.5;
if(%float)
echo("Float is not broken");
if(!%float)
echo("Float is broken");
For some reason, %float and !%float both evaluate to true, so somehow %float is true and false at the same time. Please fix this or explain to me why it works like this. !%float only evaluates to true when -1 < %float < 1.
if(%float)
echo("Float is not broken");
if(!%float)
echo("Float is broken");
For some reason, %float and !%float both evaluate to true, so somehow %float is true and false at the same time. Please fix this or explain to me why it works like this. !%float only evaluates to true when -1 < %float < 1.
Torque Owner Greg Beauchesne
In TorqueScript, all variables are stored as strings. Internally, when you do "if (condition)", Torque converts the result of "condition" to a float and then passed it to C++'s "if" statement. So, since your variable has a value of "0.5", Torque reads that as the floating-point value 0.5. That means that C++ sees "if (0.5)", which is not 0 and thus is considered true.
On the other hand, when you do "if (!%float)", the ! operator gets to your variable first and parses the string "0.5" as an integer. This means that it reads as far as "0" and then stops at "." because it encountered something that was not a valid part of an integer. !0 is 1, and so your "!%float" is considered true as well.
What will really blow your mind here is that although "!%float" is true when %float == 0.5, "!0.5" is actually false. This is because in this case, 0.5 is not stored as a string (it hasn't been run through a variable first). Instead, it is stored as an immediate floating-point value and then passed to C++'s ! operator. And again, 0.5 is not 0, so it's true, and thus !0.5 is false. This produces these curious results:
The moral of the story here is that you should not pass anything to TorqueScript's boolean constructs and operators that you know is not a boolean/integer value.