Author Topic: AS3.0 TutBits  (Read 3537 times)

0 Members and 1 Guest are viewing this topic.

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
AS3.0 TutBits
« on: July 11, 2009 »


Intro

AS3.0 TutBits is a series of small Actionscript mini tutorials. Their purpose is to point out certain differences of the actionscript 3.0 language compared to other programming languages. Each tutorial just concentrates on a tiny technical issue. The AS3.0 TutBits are not tutorials that teaches you how to programm in actionscript.

I started to release them on my personal blog - but since the blog is going through some changes - this place will be the official place for them.

---

Table of contents

1.) Getter and Setter
2.) Unknown number of parameters
3.) Nested functions
4.) Untyped variables
5.) Arrays
6.) Exception Handling
« Last Edit: July 16, 2009 by benny! »
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won:

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
Re: AS3.0 TutBits
« Reply #1 on: July 11, 2009 »
Getter and Setter

First topic is Getter and Setter. Well, I do no want to start the discussion again if they are useful or not - here it is how they are supported in Actionscript3.0:

Code: [Select]
package
{
public class GetterSetter
{
private var hiddenName:String = "OLD: Joshua";
 
public function get name():String
{
return this.hiddenName;
}
 
public function set name(newName:String):void
{
this.hiddenName = "NEW: " + newName;
}
}
 
}

On line #05, we have the class property called hidden name we want to make accessible via getter and setters. Therefore, we create two methods one line #07 and line #12 which are identified by the keyword get and set followed by the same methodname name(). With this construct you create a faked public class property called name of the class GetterSetter. You access it like a normal property using the following syntax:

Code: [Select]
var gs:GetterSetter = new GetterSetter();
trace(gs.name);
gs.name = "Joshua";
trace(gs.name);

The output of that would be:

Code: [Select]
OLD: Joshua
NEW: Joshua

That means that when you access the faked class property you actually call the respective get- or set- method. So you have the easiness of simulating direct access of a property value but still have the chance to keep control of it.

Nevertheless, this technique has some drawbacks. First, it is not possible that the property has the same name as the get/set methodname. So, if we would have named our property “name” instead of “hiddenName” it would resulted in a compile-time error. In addition, whenever you call the set method - the get method is called automatically as the result of the set method call. This hidden “feature” could also causes some confusion if you do not know that.

In the end it is up to your personal taste if you want to use this feature of actionscript or not. Of course you could implement getters and setters in the standard way writing methods like getHiddenName() and setHiddenName().
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won:

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
Re: AS3.0 TutBits
« Reply #2 on: July 11, 2009 »
Unknown number of parameters

The second TutBit is dealing with creating a method/function which takes an arbitrary number of arguments. This makes the creation of very flexible function calls possible. Have a look at the following example:

Code: [Select]
private function showFavouriteMovies( name:String, ...movies:Array ):void
{
        var retString:String = name + "'s favourite movies are: ";
 
        for (var i:uint = 0; i < movies.length; i++)
        {
                retString += movies[i];
                if ( i < (movies.length-1) )
                {
                        retString += ", ";
                }
        }
 
        trace(retString + ".");
}

The created method called showFavouriteMovies() takes two arguments. The first parameter called “name” is a normal parameter of type String. The second parameter “…movies” defines an array to hold any arguments passed to the method. The name after the “…”-construct defines the name of the array (here it is “movies”).
So, calling the function for example with the following paramters:

Code: [Select]
showFavouriteMovies("Joshua", "Wargames", "13th Floor", "The beach");

will result in:

Code: [Select]
Joshua's favourite movies are: Wargames, 13th Floor, The beach.

You see that the first named paramter called “name” can be used normally. The list of movies are stored in an indexed array where the first element (i.e. index 0) is the left-most value of the method call (in our example it is “Wargames”) proceeding to the right.

Always keep in mind, that the “…”-construct must be the last parameter in your method’s signature.
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won:

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
Re: AS3.0 TutBits
« Reply #3 on: July 11, 2009 »
Nested functions

Nested functions are functions which are defined inside a method or in other function. They are only accessible in the method/function in which they are defined. Once there is a definition of a function inside a method it does not matter if you call that nested function before its definition or after it. It works in both cases.

Here is a short example of a nested function.

Code: [Select]
private function doCalculation():void
{
        for (var i:uint; i < 10; i++)
        {
                // Do some serious calculation
                nestedLog("Calculation " + i + " done");
        }
 
        // Nested function
        function nestedLog(logTxt:String):void
        {
                trace(logTxt);
        }
}

The function defined in line 10 is only accessible in the scope of the method doCalculation(). Therefore, it is illegal to add any control access modifiers (public, private, protected) to the function.

Nested functions may be used to store some method-specific subroutines.
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won:

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
Re: AS3.0 TutBits
« Reply #4 on: July 11, 2009 »
Untyped variables

When you create a variable in ActionScript you normally add its type, e.g.

Code: [Select]
var age:uint;

Whenever you assign to that variable a value of another type the compiler will throw type mismatch errors.

Code: [Select]
// This will result in a type mismatch error
age = -10;

Actionscript provides untyped variables. You can set them explicitly with the datatype “*“, e.g.:

Code: [Select]
var anything:*;
anything = 10;
anything = "Test";
anything = new Array();

Above code will not throw any type mismatch errors, because the variable is declared as an untyped variable. So you can assign values of any kind to it.

From my personal point of view however, you should avoid using untyped variables whenever you can.
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won:

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
Re: AS3.0 TutBits
« Reply #5 on: July 12, 2009 »
Arrays

The usage of arrays in actionscript is nearly the same like the in other programming languages. However, there are some fine technical intricacies to point out.

First of all, the elements of an array in actionscript can be of different types. That means, you can put various types of elements in the same array. Following small example illustrates that:

Code: [Select]
public function Main()
{
var arr:Array = [ 1, "Two", { id:3 } ];
 
for (var i:uint = 0; i &lt; arr.length; i++)
{
trace(typeof(arr[i]));
}
// Will result in the following output:
// number
// string
// object
}

Above’s code extract creates an array called arr which holds three elements. All elements are of a different type.The element at index 0 is of type Number, index 1 is of type String and finally index 2 is an object.

Another special thing about arrays in actionscript is that the memory of arrays are allocated automatically. That means, that you do not have to care about reserving memory if you want to add elements e.g. So theroretically each array has an unlimited amount of elements. Accessing an element which actually has never been created does not resolve in an error like in other programming languages (Array index out of bounce). Refer to the following example:

Code: [Select]
// Create an array which holds 2 elements
var arr:Array = new Array(2);
 
// Now try to access the third element
// This does not result in an error like in
// other programming languages
trace(arr[2]);

Although above’s code creates an array which should hold only 2 elements, we still can try to access the third element without retrieving an error. The third element is simply undefined (i.e. equals null). Keeping this in mind, the length property returns actually the index of the last used element instead of the real amount of elements of the array. The final piece of code demonstrates the return values of length:

Code: [Select]
var arr:Array = new Array();
trace(arr.length);
arr[0] = 1;
trace(arr.length);
arr[100] = 2;
trace(arr.length);
// This code outputs:
// 0
// 1
// 101
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won:

Offline benny!

  • Senior Member
  • DBF Aficionado
  • ********
  • Posts: 4130
  • Karma: 223
  • in this place forever!
    • View Profile
    • bennyschuetz.com - mycroBlog
Re: AS3.0 TutBits
« Reply #6 on: July 16, 2009 »
Exception handling

Actionscript uses a rather loose throw convention, since you can throw nearly everything - it does not have to be an exception. The throw statement thus looks like this:

Code: [Select]
throw expression

According to that, the following code is perfectly valid and outputs “Test” :

Code: [Select]
public function Main()
{
try
{
throwSomething();
}
catch ( e:String )
{
trace(e);
}
}
 
private function throwSomething():void
{
throw new String("Test");
}

However, this is not the normal case. In actionscript you should always throw Error Objects. So, ideally above’s code should be look like this:

Code: [Select]
public function Main()
{
try
{
throwSomething();
}
catch ( e:Error )
{
trace(e.message);
}
}
 
private function throwSomething():void
{
throw new Error("Test");
}

Of course, you could write your own exception classes which derives from the Error class like you would do it in other languages with the Exception class. Apart from that difference, Actionscript’s Exception handling is pretty straight-forward and sticks to the general paradigm.
[ mycroBLOG - POUET :: whatever keeps us longing - for another breath of air - is getting rare ]

Challenge Trophies Won: