An informal survey of some of my Flash programmer buddies revealed what I’m sure you’ll agree is the most silly programmer error that we’ve all made at some point in our lives (usually many times over). It is such a trivially silly mistake that I managed to successfully do it on two different projects this year. By highlighting it here I am trying to reinforce it to the point that I never do it again. My name is Panayoti Haritatos, and I like to convert Strings into Booleans.
The Scenario
You’re reading from a text file, interpreting some global dynamically typed data, or just trying to implement meta-scripting in your game. You find that you have a string representation of some data, and you need to convert it to a boolean.
The Lie
It’s simple! Cast the string and move on… Right?
var myValue : Boolean = myString as Boolean; // pain and suffering
The Truth
var myValue : Boolean = String( "true" ) as Boolean;
trace( myValue ); // this will trace false!
What? “true” is false? It is for a pure cast.
The Fix
The fix is a two step process:
Never forget that String to Boolean has gotchas.
Use the simplest solution possible that works no matter what else might be going on.
Here’s my Boolean to String converter. The basic idea is that “true”, “TRUE”, “T”, or “t” maps to true.
var stringAsBoolean : Boolean = myString.toLowerCase().charAt( 0 ) == "t";
You may want to expand it to count “1″ as true, if binary’s more your sort of thing.
You now have the tools to live your life free from the pain of Boolean to String conversions! I’ll attach a comment to this post any time I forget and relapse. Let’s get through this challenge together!