Return statement inside try..catch block and switch statement breaks the Flash player

(Didn’t know what other title to give it, so this is what I came up with)
I came upon a strange problem a few days ago. I was trying to create a simple function that would take a String value and return that value in a simple data type (String, Boolean, Number, int or uint), based on a parameter specifying the type to return. So the easiest way was to use a switch test for all five of the types and return the value accordingly. When trying to return a Number, int or uint data type, I wanted to use a try..catch statement, just for making sure that the function would not break when using the parseFloat() and parseInt() functions. So, my function looked like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function getValue(value:String, type:String):* {
 
	switch(type) {
 
		case "String": {
			return value;
		}break;
 
		case "Boolean": {
			return (value == "true");
		}break;
 
		case "Number": {
			try {
				return parseFloat(value);
			}
			catch(e:Error) {
				return NaN;
			}
		}break;
 
		case "int": {
			try {
				return parseInt(value);
			}
			catch(e:Error) {
				return NaN;
			}
		}break;
 
		case "uint": {
			try {
				var num3:int = parseInt(value);
				if (num3 >= 0) return num3;
				else return NaN;
			}
			catch(e:Error) {
				return NaN;
			}
		}break;
 
	}
 
	return null;
}

With the function in this form, it seems that the player simply breaks down and displays a whole bunch of error messages in the Output panel. Besides those, it also displayed the entire application into compiled code, looking something like this:


verify test_switch_fla::MainTimeline/getValue()
exception[0] from=42 to=52 target=56 type=Error name=e
exception[1] from=78 to=88 target=92 type=Error name=e
exception[2] from=117 to=153 target=157 type=Error name=e
stack:
scope: [global Object$ flash.events::EventDispatcher$ flash.display::DisplayObject$ flash.display::InteractiveObject$ flash.display::DisplayObjectContainer$ flash.display::Sprite$ flash.display::MovieClip$ test_switch_fla::MainTimeline$]
locals: test_switch_fla::MainTimeline String? String? * *
0:getlocal0
stack: test_switch_fla::MainTimeline
scope: [global Object$ flash.events::EventDispatcher$ flash.display::DisplayObject$ flash.display::InteractiveObject$ flash.display::DisplayObjectContainer$ flash.display::Sprite$ flash.display::MovieClip$ test_switch_fla::MainTimeline$]
locals: test_switch_fla::MainTimeline String? String? * *

It also had a few dozen lines more of this kind. Pretty strange problem, I told myself and tried to find out why was this happening. It turns out the problem were those return NaN statements from the try..catch blocks. If I would only use the return statement, without the value to return, that would turn out to be ok (except that the function would still have to return a value and would not be correct from the application point of view).

Also, when testing the try..catch block separately, not inside the switch statement, it seems that there is no problem when the return statement is found in the catch part of the block, including the value to return. So the next code throws no errors:

1
2
3
4
5
6
7
8
9
10
11
function testing():Number {
	try {
		var test:Number = parseFloat("kdhk");
		return test;
	}
	catch(e:Error) {
		trace("catch");
		return NaN;
	}
	return NaN;
}

In conclusion, do not place return value statements in the catch blocks if those blocks are placed in switch statements. Anyway, in my case, there’s no need for the try..catch blocks, since parseFloat() and parseInt() always return a value (NaN if the source string cannot be converted), so it makes no sense using the try..catch block. After reviewing my code, here is the simple conversion function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function getValue(value:String, type:String):* {
 
	switch(type) {
 
		case "String": {
			return value;
		}break;
 
		case "Boolean": {
			return (value == "true");
		}break;
 
		case "Number": {
			return parseFloat(value);
		}break;
 
		case "int": {
			return parseInt(value);
		}break;
 
		case "uint": {
			var num3:int = parseInt(value);
			if (num3 >= 0) return num3;
			else return NaN;
		}break;
 
	}
 
	return null;
}
 
 
trace(getValue("test", "String"), getValue("test", "Boolean"), getValue("test", "Number"));
//    test false NaN
trace(getValue("12.34", "String"), getValue("12.34", "Boolean"), getValue("12.34", "Number"));
//    12.34 false 12.34
trace(getValue("-23", "Number"), getValue("-23", "int"), getValue("-23", "uint"));
//    -23 -23 NaN

Package-level functions

Sometimes, in your projects, there’s the need for a function to execute some general actions and you would need that function in multiple applications/projects. You could place that function inside a utilitarian class, import that class and then use that function. But what happens if you usually do not use the other functions defined in the class ? They would be imported as well, even if you don’t need them.

In this case you could define that function directly inside a package and not inside a class. This way, you only need to import the function you want to use. These functions defined in packages are called package-level functions. A good example of such a function is navigateToURL() from the flash.net package, used to open URLs, or getDefinitionByName() from the flash.utils package, used to get a reference to a class object.

The way to define a package-level function is quite simple. All you have to do is define that function like you would do it inside a class, with the exception that the function definition is located directly inside a package:

package myPackage {
    public_or_internal functionName(...params):DataType {
    }
}

Now, all you need to do is import the entire package (if you need it) or just that specific function (in this case the public access specifier):

import myPackage.functionName;
functionName(param1, param2...);

Note: when you save the file containing the function definition, make sure you give it the same name as the function (just like in class declarations). In this case the file name would be functionName.as.

Loader is not resizing

In ActionScrirpt 3.0 the way to load external media content like images or .swf files is to use the Loader class. The instance of this class is a DisplayObject too (actually a DisplayObjectContainer) which loads the content inside it and has to be added to display list to be viewed, just like any other DisplayObject.

The way you have to load the external content is a little bit different in AS3 using the Loader class than in AS2, using the well known MovieClip.loadMovie() method or loadMovieNum(). It resembles more on using the MovieClipLoader class from AS2.

Here is an example. If you want to load an image called flower.jpg and display it, here’s what you have to do:

  • - create the loader object:
    var loaderObject:Loader = new Loader();

  • - set the coordinates:
    loaderObject.x = 150;
    loaderObject.y = 45;

  • - add the loader to the display list:
    addChild(loaderObject);

At this point, anything you load inside it will be visible on the stage. If you would load the content without adding the loader object to the stage, there wouldn’t be anything displayed until the addChild() method call.

  • - you need to create a URLRequest object which is based on the URL of the content itself:
    var request:URLRequest = new URLRequest("flower.jpg");

  • - now you can instruct the Loader instance to load the image:
    loaderObject.load(request);

You could use a shortcut and combine the previous two lines into a single line of code:

loaderObject.load(new URLRequest("flower.jpg"));

Sometimes the content you want to load has a larger size than the stage or the area where you want to display it. So, you’ll have to resize the loader. Doing it write after the load() method call would result in not displaying anything, even if the content has been successfully loaded. This is because the loader gets resized after the load() method but before the content gets fully loaded (especially if it has a larger file size).

The solution for this problem is to always resize the Loader object after the content has completely loaded. To do this, you need to listen for the event the loader dispatches when it finishes loading the content: Event.COMPLETE:

loaderObject.contentLoaderInfo.addEventListener(Event.COMPLETE, resizeLoader);

function resizeLoader(evtObj:Event):void {
    loaderObject.width = 400;
    loaderObject.height = 300;
}

How to use Timer class instead of setInterval()

In ActionScript 3.0, the preferred way to execute actions at specific time intervals is the use of the new Timer class. In ActionScript 2.0, we had the setInterval() function and this was the way to use it:
- write a function that would be called every time the time interval passed the limit
- call the setInterval() function that would receive as parameters the object that has the target function defined (not always necessary), the name of the function (or a reference to it), the time interval at which to call the target function and the list of parameters for the target function (also not necessary)
- to stop the time interval there should have also been a variable defined to hold the interval id and then call clearInterval() with the interval’s id as parameter.

AS2 example – call a function 10 times

For example, the next piece of code will call timeHandler 10 times and then interrupt the repeated calls of the function:

var counter:Number = 0;
var intervalID:Number;

function timerHandler(param:String):Void {
counter++;
trace(“This function has been called “+counter+” times with the \”"+param+”\” parameter”);
if (counter == 10) clearInterval(intervalID);
}

intervalID = setInterval(timerHandler, 1000, “test”);

AS3 example

For AS3, the steps are similar but setInterval() was replaced by the Timer class. Here is the above code translated into AS3:

import flash.utils.Timer;
import flash.events.TimerEvent;

var counter:int = 0;
var timerObject:Timer = new Timer(1000, 10);
timerObject.addEventListener(TimerEvent.TIMER, timerHandler);
timerObject.start();

function timerHandler(eventObject:TimerEvent):void {
counter++;
trace(“This function has been called “+counter+” times”);
}

AS3 code explained

You can see that when creating a new instance of the Timer class, the constructor has two parameters passed to it: the first is the time interval (in milliseconds) and the second is the number of repetitions, that is the number of times to call the handler function. If the second parameter is not given or it’s 0, then the timer repeats infinitely. Next, you need to define the handler function for the TimerEvent.TIMER event, which gets dispatched every time the time interval is passed. The Timer class also dispatches another event, TimerEvent.TIMER_COMPLETE. This event is dispatched only when the timer object has finished the number of repetitions. If the repeatCount, the second parameter of the Timer constructor is not defined or it’s 0, then the TIMER_COMPLETE event will never get called. Once you create the Timer instance, you need to start it (timerObject.start()) otherwise it won’t have any effect.

As you can see, for the AS3 version, you cannot pass any parameters directly to the timer event handler functions. If you want to get the same result as the AS2 example, then you need to create another function that would be called by the timer event handler and get the parameter passed to this second function:

function timerHandler(eventObject:TimerEvent):void {
callback(“test”);
}

function callback(param:String):void {
counter++;
trace(“This function has been called “+counter+” times with the \”"+param+”\” parameter”);
}

The Timer class

The Timer object is more complex and offers us more information on the current interval calls. We can have access to the number of repetitions the Timer object has reached (timerObject.currentCount), the total number of repetitions (timerObject.repeatCount), the time interval (timerObject.delay) and we can even find out if the Timer object is running or not (timerObject.running).

By using the Timer class, you also have the ability to stop the repetitions (timerObject.stop()) and then resume it, if you call the start() method again. It even has the possibility to reset the counter (timerOject.reset()) and the Timer object will start the repetitions all over again.

Get the number of repetitions from the Timer object

As mentioned previously, you can access different parameters of the Timer object and you can do it even in the timer event handler function. The next example displays the number of times the function has been called, without having to define an extra variable for that:

import flash.utils.Timer;
import flash.events.TimerEvent;

var timerObject:Timer = new Timer(1000, 10);
timerObject.addEventListener(TimerEvent.TIMER, timerHandler);
timerObject.start();

function timerHandler(eventObject:TimerEvent):void {
trace(eventObject.target.currentCount+” repetitions out of “+eventObject.target.repeatCount);
}

As you can see, the Timer class is a welcome addition to the ActionScript 3 framework. Enjoy it.

Promotion for text effect with reflection

Jumpeye has just launched a short promotion for a limited edition of TxEff: TxEff with reflection. All you have to do is to create your own text animation on www.txeff.com, save it and then embed it into your own site using the HTML code provided on txeff.com. Just like I did…

Hurry up ! It’s only available for a few days…

Flash Text Effects – How Easy It Is ?

There are a few ways to create text effects using Flash, like alpha or blur animations, color changing, text scaling or moving text and these are relatively easy to do. But what happens if you’ve seen some fancy text effect on a site or even in a video clip, perhaps in a movie, and you want that exact effect in your Flash banner, presentation or site ? It is highly unlikely that the effect was made with Flash. Chances are it was made with some professional tool for video editing.

If you want to have that same effect replicated in Flash, that means you’re going to work for the next few nights and write a lot of code to get there. Yes… if you’re a Flash and ActionScript pro… But what if you’re a rookie… Maybe you’ve never written code before. What then ?

Then, you should use this great tool developed by us at Jumpeye Creative Media. It’s called TxEff. This is a Flash CS3 component (only works with ActionScript 3.0) which you can use to create amazing text effects in Flash, literally in a few minutes, with just a few mouse clicks and a few parameter settings. That’s how easy has become creating Flash text effects. The animation below took me 15 minutes to complete (including testing more parameters to get the effect I wanted and consulting the help pages to get more info on some parameters).

Another great thing about it is that there is a free version of the component, that comes with three patterns embedded into it. You can use these patterns to create a large number of effects, number limited only by your imagination. You can download the component from JumpeyeComponents’ site but you’ll need an account for that (if you don’t have one, go ahead an create it). On the same site, you have access to several tutorials to get you started, the component’s help pages and documentation on all the patterns and their presets. These patterns are actually extensions of the component, so you’ll need both the component and the pattern into the Library, to create an effect. JumpeyeComponents also has a Knowledge Base, containing solutions to a few common questions regarding TxEff.

Besides all these, the component’s site (www.txeff.com) is actually a large effects database, created by all the people visiting the site. If you like an effect there, you can easily import it into your project (just remember to have that pattern into your Library).

Let me give you a piece of advice: before starting to work with TxEff, try to go through the documentation. The component is quite complex, even though it is easy to use, and has a few limitations and requirements. Also try to check out some of the tutorials to get a better idea of what TxEff can do. If you’re having problems with integrating the component, you should read the documentation first or check out the knowledge base… Chances are that you’ll find the answer to your problem there. If not… JumpeyeComponents support team will happily help you out.

Download source files

5005: Unknown error optimizing byte code

This is a really “interesting” error message that Flash throws in the Output panel and unfortunately there is no other explanation accompanying the message. At Jumpeye we’ve had to deal a few times with this error message which seems to be generated whenever working with large .fla files that make use of rather large amounts of code.

The solution would be to turn off the Optimizer and then recompile. You can turn the Optimizer off from the Publish Settings dialog box, select Settings for the “ActionScript 3.0″ option and in that dialog box disable the “Reduce file size and increase performance” option. You can do this whenever you are working on a very large project and get this error message. In the rest of the cases, you should leave this option checked.

Another solution I’ve found on the web (didn’t test it) is to delete the .aso files generated by Flash (Control -> Delete ASO Files) .

Access FlashVars parameters with AS3

Many people use FlashVars as a way to send parameters to the flash movie playing in the browser. This way the parameters are imported as root level variables.

Using ActionScript 1 and 2 these variables can be accessed easily from the root level, like this: _root.parameterName. So, if you would send two parameters and their values (xmlFile=setup.xml&imageFile=picture.jpg) to the flash movie, you would access their values like this:

trace(“the xml file is: “+_root.xmlFile);
trace(“the image file is: “+_root.imageFile);

This changes when it comes to ActionScript 3. You cannot access _root.xmlFile or _root.imageFile, simply because these variables do not exist on the root level. They haven’t been declared so the compiler throws an error. The new way to access the FlashVars parameters using ActionScript 3 is to use the LoaderInfo class. Every DisplayObject contains a property called loaderInfo which is an instance of the LoaderInfo class. An object of this class contains a property called parameters. This is an object that enumerates the list of FlashVars parameters and their values. You would access these parameters like this:

var paramList:Object = this.root.loaderInfo.parameters;
trace(“the xml file is: “+paramList["xmlFile"]); // you could also use paramList.xmlFile
trace(“the image file is: “+paramList["imageFile"]); // and paramList.imageFile

Get Flash player version with AS3

Recently I’ve posted on jumpeyecomponents’ Knowledge base an item, for the TxEff component, that shows you how to detect the version of the current Flash player, using ActionScript 3 code.

The only difference between AS2 and AS3 in this case is the method to get the Flash player’s version. AS2 has the getVersion() method. In AS3, there is the flash.system.Capabilities class which has a property called version. In both cases you’ll get a String representing the platform on which Flash player runs and the version. The result looks like this: “WIN 9,0,115,0″ (for the 9.0.115 Flash player on Windows).

What does this String mean ? Well, the first letters are the platform on which Flash player runs. This could be “WIN”, for Windows, “MAC” for Mac OS and “UNIX” for Unix based operating systems. Then comes the actual version number of the player. The first number represents the major version number. Next comes the minor version number. Third is the build number and the last one is the internal build number.

The next code snippet, separates the version String into the corresponding parts and displays them:

import flash.system.Capabilities;

// Get the player’s version by using the flash.system.Capabilities class.
var versionNumber:String = Capabilities.version;
trace(“versionNumber: “+versionNumber);

// The version number is a list of items divided by “,”
var versionArray:Array = versionNumber.split(“,”);
var length:Number = versionArray.length;

// The main version contains the OS type too so we split it in two
// and we’ll have the OS type and the major version number separately.
var platformAndVersion:Array = versionArray[0].split(” “);

var majorVersion:Number = parseInt(platformAndVersion[1]);
var minorVersion:Number = parseInt(versionArray[1]);
var buildNumber:Number = parseInt(versionArray[2]);

trace(“Platform: “+platformAndVersion[0]);
trace(“Major version: “+majorVersion);
trace(“Minor version: “+minorVersion);
trace(“Build number: “+buildNumber);