Archive

Posts Tagged ‘typing’

AS3 Mystery: null, false, 0, “”, NaN

April 2nd, 2009 2 comments

This week I’ve been running unit tests and couldn’t understand why some of them were failing for no obvious reason. To understand why some expressions evaluated to true when they were supposed to be false. I know that I should be careful with null vs false values, but never could I have imagined that the Number 0 can be equal to an empty String!

I know that php’s empty() function is quite permissive, but I though AS3 was much more strict (with strict typing and all). And so I ran a different kind of test, where I checked these values in depth. Here is a table describing my results.

  null false 0 “” NaN
isNaN()          true
== “”   true true true  
=== “”       true  
== null true        
=== null true        
== 0   true true true  
=== 0     true    
== false   true true true  
=== false   true      
is Number     true   true
is String       true  
is Boolean   true      
is Object   true true true true

 You will notice that NaN is actually a Number and an Object, that 0 == “” == false and that false is actually an Object. There are quite a few surprises in there that will make me appreciate strict comparison.

Tags: ,

if (value is Object) problem

January 8th, 2009 8 comments

To my knowledge, everything is AS3 an object. Functions, Strings, Arrays…

So how do we check if our value is actually an Object? I had this problem in a for loop. I wanted to treat primitive types, Arrays and Objects differently. My first reaction was to test for Arrays, then for Objects and handle the rest in the else block. Well remember that if you check if a String is an Object, you’ll get a false positive.

Solution:

var className:Object = getQualifiedClassName(value);
if (className == 'Object') {
    // do stuff here
} 
else if (className == 'Array') {
    // do stuff here
}  
else {
    // do stuff here
} 
Tags: ,

Working with types in AS3

January 24th, 2008 No comments

ActionScript 3 is strong-typed, which is great to detect possible errors at compile-time. Here are a few tips for working with types.

Type wildcard

var someVar:*;

This is not recommended (can cause runtime errors) but is possible. I suggest using a common parent (DisplayObject, for example) whenever possible.

Type checking

if (someVar is MovieClip) {}

This is most useful. Example: getting the list of MovieClip children from a parent MovieClip (you don’t want shapes and all). This line might prevent the whole app from blowing up in your face.

Type casting

var item:Object = ComboBox(event.currentTarget).selectedItem;

This will prevent type-mismatch complile errors. The same applies to simple types, such as int and uint.

Tags: ,