kirupaForum

kirupaForum (http://www.kirupa.com/forum/index.php)
-   Flash ActionScript (http://www.kirupa.com/forum/forumdisplay.php?f=9)
-   -   ActionScript 3.0 Tip of the Day (http://www.kirupa.com/forum/showthread.php?t=223798)

senocular 06-19-2006 05:02 PM

ActionScript 3.0 Tip of the Day
 
The release of Flex Builder 2 is around the corner and though the next version of Flash is still a ways away, ActionScript 3 will be a big part of Flex 2 and the impending release of Flash Player 9 (which arrives with Flex). ActionScript 3 is the next step forward and to help with the transition (for those of you deciding to make it), I thought, since I've been working with AS3 a bit lately, I'd make a new Tip of the Day thread for ActionScript 3 to help people prepare. So here we go:

ActionScript 3 Tips and Tricks:
  1. 06-19-06: Change the frame rate of your movie
  2. 06-20-06: Class scope is now bound to class methods
  3. 06-21-06: Graphics Object and the Drawing API
  4. 06-22-06: New Variable Types
  5. 06-23-06: Display Objects
  6. 06-24-06: New Import Directive
  7. 06-25-06: Type Casting and the as Operator
  8. 06-26-06: Unique Class Variables
  9. 06-27-06: New MouseMove Behavior
  10. 06-28-06: The delete Keyword and Class Members
  11. 06-29-06: The Dictionary Class
  12. 06-30-06: Label Statements
  13. 07-01-06: Detecting When the Mouse Leaves the Movie
  14. 07-02-06: SimpleButton Instances
  15. 07-03-06: Commas in Shorthand Array Definitions
  16. 07-04-06: Package Block
  17. 07-05-06: Same-file Helper Classes
  18. 07-06-06: Access Attributes
  19. 07-07-06: Abstract Classes
  20. 07-08-06: The override Keyword
  21. 07-09-06: Using prototype
  22. 07-10-06: Regular Expression (RegExp) Support
  23. 07-11-06: Approach to Depth Sorting
  24. 07-12-06: Deep Object Copies with ByteArray
  25. 07-13-06: Similarly Named Instance and Static Properties
  26. 07-14-06: EventDispatcher
  27. 07-15-06: Events and Event Types
  28. 07-16-06: Writing Inline XML
  29. 07-17-06: Determine Instance Class or Superclass
  30. 07-18-06: super() Placement (Now Anywhere)
  31. 07-19-06: Determining Current Frame Label
  32. 07-20-06: Multiple Arguments in trace()
  33. 07-21-06: Calling Event Handlers without Events
  34. 07-22-06: URLRequest for URL Strings
  35. 07-23-06: XML vs. XMLDocument
  36. 07-24-06: Loading Text and XML with URLLoader
  37. 07-25-06: is Operator (vs instanceof)
  38. 07-26-06: Flash 9: Timelines as Classes
  39. 07-27-06: RegExp: Email Validation
  40. 07-28-06: Render Event
  41. 07-29-06: XML: @ Operator for Attributes
  42. 07-30-06: Event Propagation Support
_______________________________________

Additional Resources:Download:

senocular 06-19-2006 05:03 PM

Change the frame rate of your movie
 
Using ActionScript 3, you can dynamically change the frame rate of your movie using the Stage class.

The Stage class (flash.display.Stage) is the class assigned to the stage object which is accessible from your main movie sprite/movie clip (or others within the same security sandbox) using the stage property. The stage object has a frameRate property which can contain any value between 0.01 and 1000 and determines the frame rate at which the Flash player plays back your movie. Changing this value lets you change the frame rate at runtime.

ActionScript Code:

// change frame rate to 12 fps:
stage.frameRate = 12;


mathew.er 06-19-2006 06:08 PM

Nice to have an AS 3 thread. Maybe whole Flex/AS3 forum would be usefull as it seem to spred a lot.

To the stage thing... is "stage" and not "Stage" a typo or do you need to import and instance the Stage to change the framerate? Shouldnt flash.display.Stage.frameRate = 12 do the job then?

REEFˇ 06-19-2006 06:18 PM

Changing FPS with AS? Isnt this a dream come true?

TheCanadian 06-19-2006 06:26 PM

Quote:

Originally Posted by mathew.er
Nice to have an AS 3 thread. Maybe whole Flex/AS3 forum would be usefull as it seem to spred a lot.

To the stage thing... is "stage" and not "Stage" a typo or do you need to import and instance the Stage to change the framerate? Shouldnt flash.display.Stage.frameRate = 12 do the job then?

No, in AS3 it has changed - the Stage class is accessed through the stage property of a DisplayObject instance. However, they all reference the same thing I think.

ieatcotten 06-19-2006 10:33 PM

Quote:

However, they all reference the same thing I think.

Thats how I understand it.
Quote:

Inheritance:Stage->DisplayObjectContainer-> InteractiveObject->DisplayObject ->EventDispatcher->Object

The Stage class represents the main drawing area. The Stage represents the entire area where Flash content is shown.

The Stage object is not globally accessible. You need to access it through the stage property of a DisplayObject instance.


http://livedocs.macromedia.com/labs/...lay/Stage.html

mathew.er 06-19-2006 11:27 PM

So that example at livedocs makes it pretty clear... "stage" is a global object allowing you to view and change its properties or to register events with it.
ActionScript Code:

package {
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;

    public class StageExample extends Sprite {

        public function StageExample() {
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;
            stage.addEventListener(Event.ACTIVATE, activateHandler);
            stage.addEventListener(Event.RESIZE, resizeHandler);
        }

        private function activateHandler(event:Event):void {
            trace("activateHandler: " + event);
        }

        private function resizeHandler(event:Event):void {
            trace("resizeHandler: " + event);
            trace("stageWidth: " + stage.stageWidth + " stageHeight: " + stage.stageHeight);
        }
    }
}


@fabiopb: Why? Isnt this just a sign, that flash goes on pretty well? If your worried anout the Adobe Flash application itself, then you dont need to be... Flex is just for something else than Flash. It wont also disappear from the Internet as everybody has the plugin, people are used to use it and it still has great potential.

sandeep_cdac200 06-19-2006 11:34 PM

one more step towards making AS to Java!! Great!!

senocular 06-20-2006 06:55 AM

Quote:

Originally Posted by sandeep_cdac200
one more step towards making AS to Java!! Great!!

There are more steps to come that reinforce this idea ;)

senocular 06-20-2006 07:12 AM

Class scope is now bound to class methods
 
ActionScript 3 is entirely class-based. When you create classes, you create variables and functions (methods) which relate to and work with that class and instances of that class. Unlike ActionScript 2, methods in ActionScript 3 now retain their class scope when called, even if assigned to another object and called from that object, or if used with Function.call and Function.apply. Example:

ActionScript Code:

package {
    import flash.display.Sprite;
   
    public class ClassScope extends Sprite {
       
        public function ClassScope() {     
            traceThis(); // "Class Instance"
           
            var obj:Object = new Object();
            obj.traceThis = traceThis;
            obj.traceThis(); // "Class Instance"
           
            traceThis.call(new Sprite()); // "Class Instance"
        }

        public override function toString():String {
            return "Class Instance";
        }
       
        public function traceThis():void {
            trace(this);
        }
    }
}


sepu 06-20-2006 09:09 AM

this topic at least should be a sticky !
thx Senocular.

senocular 06-20-2006 09:28 AM

Quote:

Originally Posted by sepu
this topic at least should be a sticky !
thx Senocular.

Since it's every day it won't have problems staying near the top ;)

icio 06-20-2006 09:42 AM

Nice one, sen :thumb:

REEFˇ 06-20-2006 10:51 AM

A few questions...Whats AS 3.0 for? Is there a new flash coming out?

And PK...why do you believe flash will decline?

senocular 06-20-2006 10:59 AM

Quote:

Originally Posted by ~REEF~
A few questions...Whats AS 3.0 for? Is there a new flash coming out?

ActionScript 3 is the next release of ActionScript that will be supported in Flash Player 9. Flex 2 applications are built using ActionScript 3 and the next version of Flash (code named BLAZE) will support it when it's released some time after Flex. Unlike ActionScript 2, ActionScript 3 uses an entirely new virtual machine providing it with new robust features and increased performance.

More details on available and upcoming products can be found on http://www.adobe.com/ and http://labs.adobe.com/ (where both the Flex 2 beta and Flash Player 9 beta are currently available for download)

FatalDisruption 06-20-2006 10:34 PM

Hey sen, how much work do you think it'll take to convert an AS2 class to a fully optimized AS3? I'm assuming it would take just a few changes to make it work, but an entire rewrite to take advantage of all AS3+F9 features. Have you tried converting any of your classes to 3 yet?

Working with a project that has a few thousand lines of code, it seems like a daunting task. Because there's things like attachMovie that aren't even there anymore, so it's not like easy AS1 to AS2, correct?

senocular 06-21-2006 09:36 AM

Quote:

Originally Posted by FatalDisruption
Hey sen, how much work do you think it'll take to convert an AS2 class to a fully optimized AS3? I'm assuming it would take just a few changes to make it work, but an entire rewrite to take advantage of all AS3+F9 features. Have you tried converting any of your classes to 3 yet?

Working with a project that has a few thousand lines of code, it seems like a daunting task. Because there's things like attachMovie that aren't even there anymore, so it's not like easy AS1 to AS2, correct?


It depends. Some conversions aren't that bad. However, with the new scoping behaviors of AS3, there can be some drastic changes. Also, another thing to consider is default values for some variable types. Declared but undefined Number variable instances, for example, are no longer undefined but NaN and to check to see if they have been defined you should use isNaN(myNum) and not myNum == undefined.

There are also a lot of little things that have to be modified, such as adding the package {} block, using the override keyword, and changing all instances of Void to void (and not using void if methods have no arguments).

I've only converted my Path class at this point, and I think that was only (if) a couple hundred lines. It wasn't too bad at all, but I know there are some other classes I think I would fear to convert.

senocular 06-21-2006 09:50 AM

Graphics Object and the Drawing API
 
Like ActionScript 1 and 2, ActionScript 3 also has a drawing API that allows you to draw vector lines and shapes dynamically in movie clips and sprites. With ActionScript 3, however, the drawing API is now used off of an object within display objects (movie clips, sprites, etc.) defined as graphics (flash.display.Graphics). This graphics property represents the dynamic drawing layer where drawing API drawings exist. Like before, it is placed below all children of the target object. Also, in ActionScript 3, you have new methods that help you more easily create rectangles, circles, and even rounded rectangles. These include:
  • drawCircle(x:Number, y:Number, radius:Number):void
  • drawEllipse(x:Number, y:Number, width:Number, height:Number):void
  • drawRect(x:Number, y:Number, width:Number, height:Number):void
  • drawRoundRect(x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number, ellipseHeight:Number):void

Example:
ActionScript Code:

// draw a blue rounded rectangle:
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF);
square.graphics.drawRoundRect(0, 0, 100, 50, 10, 10);
square.graphics.endFill();
addChild(square);


senocular 06-22-2006 06:19 AM

New Variable Types
 
ActionScript 3 supports a wide range of variable types including some which were not present in previous versions of ActionScript. Basic types for AS3 include:

Primitive:
  • Boolean
  • int
  • null
  • Number
  • String
  • uint
  • undefined
Complex:
  • Object
  • Array
  • Date
  • Error
  • Function
  • RegExp
  • XML
  • XMLList

Additional types also exist that relate to their classes; ex: Matrix (flash.geom.Matrix), Shape (flash.display.Shape), URLRequest (flash.net.URLRequest), etc.

Things to note:
  • The special Void type has changed in AS3 to be lowercase (void not Void)
  • There's a new * type that is used to represent any data type. This should be used instead of ommitting typing information for your variables.
    ActionScript Code:

    var anything:*;

  • The XML type is not the same as the XML type in ActionScript 1 and 2. The old XML type (object) is now defined as XMLObject. XML now references the new E4X-based XML object.
  • int and uint are new primitive number data types for integer (numbers without decimal values) and unsigned integer (numbers without decimal values that also cannot be negative). These can be useful for values which are not supposed to have decimal values such as loop iterators. The int data type will provide a small perfomance boost when used over Number in most cases, but uint should only be used when necessary such as with color values.

senocular 06-23-2006 06:24 AM

Display Objects
 
ActionScript 3 now has a new collection of "display objects" which includes those objects that can be seen on the screen or added to the "display list." This goes beyond the simple movie clip, button, and text field objects that ActionScript had access to before. AS3 display objects include
  • AVM1Movie
  • Bitmap
  • Loader
  • MorphShape*
  • MovieClip
  • Shape
  • SimpleButton
  • Sprite
  • StaticText*
  • TextField
  • Video
*Are for referencing pre-existing objects existing on the timeline; you cannot create them via AS.

AVM1Movie represents a movie created with ActionScript 1 or 2. Those movies use ActionScript Virtual Maching 1 where AS3 movies use AVM2. AVM2 movies can play AVM1 movies, but cannot interact with them (their ActionScript) using AS3.

Bitmaps are bitmap objects. You can specify their imagery with BitmapData objects or they can be bitmaps from files.

Loader objects are display objects that load external content into them. This content can be images or other SWF movies.

MorphShapes are shape tweens created in the timeline. Though you cannot create them in ActionScript, you can access those that exist on the timeline already using ActionScript and they are of the type MorphShape.

MovieClips are the movie clips you know and love.

Shapes are stripped down movie clips that essentially only contain a graphics object for drawing in with the vector drawing API. Using Shapes instead of MovieClips or Sprites can help conserve memory

Sprite objects are essentially movie clips without timelines. This is your most common display object in AS3 and usually the one extended when creating your own display object subclasses.

StaticText, like MorphShapes, cannot be created with ActionScript instead referening static text objects that are pre-existing on the Flash timeline.

TextField objects include dynamic and input text.

Video objects represent Flash video.

senocular 06-24-2006 08:07 AM

New Import Directive
 
The import directive in ActionScript 3 is a little different than import in ActionScript 2. In AS2, import was used solely as a name shortener for classes defined in packages; it was not required to use a class. Instead of using import, you could just have used the class's full name. ex:
ActionScript Code:

// ActionScript 2
var myPoint:flash.geom.Point = new flash.geom.Point(0,0);


In ActionScript 3, the import directive is required to access classes in their packages, even if you reference the class using its full name. You can still use the full name (or just the imported class name), but the import is required
ActionScript Code:

// ActionScript 3
import flash.geom.Point;
var myPoint:flash.geom.Point = new flash.geom.Point(0,0);


As with AS2, you can also use the wildcard character (*) in AS3 to import all classes within a package.
ActionScript Code:

import flash.geom.*;


Krilnon 06-24-2006 08:36 AM

How did I not see this thread until today? :-/

Why are the rules /suggestions for using uint so strict? Is it not as fast as an int variable? In other words, I see no reason not to use uint for every value that I know will be a positive integer, why isn't this the case?

When using addChild and getChild-type methods, you are allowed to add objects that are subclasses of DisplayObject, but the 'get' functions all return DisplayObjects. I'm assuming that this is done so the method will have only one return type, but it is kind of inconvenient to have to construct subclass-typed objects out of that returned value, like "Bitmap(imageHolder.getChildAt(0))". Is there a better way of handling returns that return value types that are less specific than you would like?

How do you make functions callable by events and non-events with more than just an event as an argument? In your CoilGallery source, I saw that you had something like "event:Event = null", which I'm assuming makes the argument optional. I've been running into trouble using functions for multiple purposes that need specific argument types. If I, for example, had a function that for some reason needed to have the x property of a DisplayObject. If I wanted to be able to call this function with an event and by itself, would it be best to define the function so it can be run by itself and then have a separate function that serves as an event handler to get the desired property using info from the event.target and then passes that into the function with the x argument?

senocular 06-24-2006 08:54 AM

1. Yes, uints are pretty slow. I don't know why, but they are. Typically they're just used for numbers that require values that high (like colors with alpha information). Using int for integers is generally a little faster than Number (but not much if at all in all situations). All in all, using only Number wouldn't kill you. They might get around to optimizing int (and maybe uint?) more in the future, though. So its good practice to use them where applicable. For more info see:
http://kuwamoto.org/2006/06/15/avoid...-actionscript/

2. The getChild methods all return DisplayObject types because methods are only allowed to have one type associated with their return value. By using DisplayObject, its using a type that all objects must be or inherit from to even be added in the first place. So if you add something to the display list, you know it's at least going to be a DisplayObject and having the return value typed as that means it works for whatever is returned.

Note: You can also use the 'as' operator to change the type of variables (and I think this is preferred over ClassCast() conversions).

ActionScript Code:

var myBmp:Bitmap = imageHolder.getChildAt(0) as Bitmap;



3. In using event:Event = null as the parameter for a method, I was able to use it both as an event (where the event object is passed) and as a normal method call anywhere else in my code using methodName(); since having a default value for parameters makes them optional. Required parameters have no default value. You can have both as well, but optional have to come after all required.

If you want to have a method that acts as an even handler and a normal method, if its "normal" use doesn't use an event parameter as the first parameter, then you'll most likely just have to use a separate method for the event handler that calls your normal event.

There is also a new ...(rest) parameter that lets you specify an undetermined number of untyped arguments. Arguments that map themselves to the ...(rest) parameter are assigned to an array with the name of (rest) which you can name anything you want. I'm pretty sure I used this for the trace method in the Output class (com.senocular.utils.Output). That should use it by itself as one parameter, but you can also have required parameters come before it. You can find more information in the docs under
Language Elements > Statements, Keywords & Directives > [Definition keyword summary] ...(rest)

Krilnon 06-24-2006 09:11 AM

Thanks senocular! :beam:

Quote:

Note: You can also use the 'as' operator to change the type of variables (and I think this is preferred over ClassCast() conversions).

That's just what I was looking for. I had seen the 'as' operator before (in your CoilGallery, I think), but it makes much more sense when applied to a situation that I'm familiar with.

senocular 06-26-2006 08:12 AM

Type Casting and the as Operator
 
ActionScript lets you change the assigned type of an object to other compatible types when needed. This is called casting. Both ActionScript 2 and 3 support casting using type(object) syntax. For example, if your custom class object was assigned to a variable typed as an object, you can reassign typing for that object by casting it to have a type of your custom class thereby letting Flash know what methods and properties exactly are available to that object
ActionScript Code:

var obj:Object = getMyCustomObject();
vay customObj:MyClass = MyClass(obj);


ActionScript 3 introduces a new operator for casting, the as operator. The as operator replaces casting using type(object) in ActionScript 2 with a syntax of object as type.
ActionScript Code:

var obj:Object = getMyCustomObject();
vay customObj:MyClass = obj as MyClass;


The as operator works much like casting in ActionScript 2. If the conversion can't be made, the result of the cast is null. Otherwise, the object being cast is returned and assigned a type of the type used.

ActionScript 3 still supports type(object) casting, but the behavior is a little different now. Instead of returning null for failed casting, a TypeError is thrown. Failure occurs when you try to cast an object into an incompatible type such as trying to cast one object into a type it is not associated with or inherits from.

Note: ActionScript also has global conversion functions in that work in the style of Class(object) which have precedence over type(object) casting. These include String(), Number(), and Array(), etc. These don't cast so much as actually convert one object into another (where applicable). Because these have precedence over type(object) casting, its preferred that the as operator be used when casting objects to different data types.

senocular 06-26-2006 08:23 AM

Unique Class Variables
 
In ActionScript 2, variables defined within a class's body were defined in the class's prototype object. This was an efficient means to handle variable definitions but it also meant that complex data types (such as Arrays) had a tendency to be "shared" among instances if not explicitly defined for instances within the class constructor. This is no longer a problem with ActionScript 3. Class variables defined in the class body are now unique to each class instance so this problem no longer occurs.
ActionScript Code:

class myClass{
   
    private var list:Array = [1,2,3]; // bad for AS2, ok for AS3
           
    public function myClass(){
        // list should be defined here for AS2
    }
}


senocular 06-27-2006 11:09 AM

New MouseMove Behavior
 
The mouseMove event has changed a little in ActionScript 3. Before, mouseMove events were global meaning that no matter where the mouse was in the Flash movie, if it moved, any listener to Mouse or any MovieClip (which automatically receive mouse events without being made listeners of Mouse) would recognise that it moved and recieve the event.

With ActionScript 3, the Mouse object is no longer used for dispatching mouse events. For mouseMove events, you would listen to InteractiveObject instances such as Sprites, MovieClips, and the Stage. So instead of adding listeners to Mouse, you would use some InteractiveObject. For each InteractiveObject instance, though, the mouseMove event is only called when the mouse moves from one location on that object to another location on that object. For a mouseMove event anywhere in the movie, you would want to add your listener(s) to the Stage instance.

Given this behavior, when using mouseMove to drag objects, you would always want to use Stage as your dispatcher in the case that when you move the mouse, the location it moves is off the object your dragging. If that were to happen, the mouseMove event wouldnt not fire and your drag would stop.

ActionScript Code:

stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMyObject);


Krilnon 06-27-2006 01:59 PM

Quote:

With ActionScript 3, the Mouse object no longer exists

Doesn't it exist, just not in the way it did before? For example,
ActionScript Code:

trace(typeof(Mouse));

That traces "object", so Mouse still exists as an object, right? It just has two static methods and everything that it inherits.

As far as dragging goes, has startDrag (and stopDrag) been improved at all? I always avoided it in Flash <9, but I tried to use it again for the AS Battle and ended up falling back on hand coding it with if constraints. The built-in function seems to be more trouble than it's worth, so is there any case where it would be better to use startDrag? (Perhaps when I have a predefined rectangle that might be changed dynamically?)

senocular 06-27-2006 02:13 PM

Yeah, I meant to say its no longer an object that you add listeners too - lemme edit that ;) Mouse does exist, but for a different reason - mainly just to control whether or not the mouse cursor is seen (I think that actually may be it too)

AS for startDrag, I dont think it has changed much.

JoshuaJonah 06-27-2006 02:19 PM

ActionScript 1.0 Tip of the day: Upgrade

:D

Krilnon 06-28-2006 07:19 AM

I have a suggestion for today's hint: Describe how to use AS 3.0 classes with the Flash 9 preview. I'm trying to get my gallery to work with it, though I haven't had any luck so far. (I've only had it for 10 minutes, though)

ActionScript Code:

var myGallery:KrilGallery = new KrilGallery<font color="#000000">(</font><font color="#000000">)</font>;



Generates:
Quote:

Originally Posted by Runtime Error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at KrilGallery$iinit()
at Timeline0_6f3f7df53146e840b3f92ad2f63d7757/::frame1()


It does run the first line of the constructor function, though, as it traces "KrilGallery". The next line tries to access the stage, so perhaps that is part of the issue.

senocular 06-28-2006 07:34 AM

Krilnon, all you do is type your class in the document class field in the property inspector then publish.

Your application class is setup to represent the actual movie being published (the document class). Just making a new instance of it on the timeline only creates an instance in a default document class and your movie won't function as expected. :)

Krilnon 06-28-2006 07:57 AM

Oh, that makes things much more simple. Thanks :)

senocular 06-28-2006 08:11 AM

The delete Keyword and Class Members
 
The delete keyword in Flash is used to remove variable definitions. It doesn't delete objects from memory (this happens behind the scenes using something called the "Garbage Collector"), it just takes a variable you've created and gets rid of it so that it is no longer accessible and is no longer present through iteration (for..in loops, etc.).

Internally, the Garbage Collector, or GC for short, knows when to physicially delete objects in memory when they no longer have any variables that reference them. So, for example, if you have two variables A and B and they both reference ObjectX, deleting variable A will not cause ObjectX to be removed from memory by the GC because variable B still references it. However, if you delete both variables A and B, there will be no more references to ObjectX and the GC will recognize that it needs to be removed from memory
ActionScript Code:

var a:Object = new Object();
var b:Object = a; // reference same new Object();
delete a;
trace(b); // [object Object] - still exists in memory
delete b;
// GC will mark object for deletion from memory
 


This works practically the same way for Flash 8 and Flash 9 (ActionScript 1, 2, and 3), though some changes were made in 8 to improve the GC. (Note: GC deletion from memory is not immediate.)

Though the GC has not really changed much with ActionScript 3 and the new virtual machine that runs it, what has changed is the behavior of the delete keyword. Now, the delete keyword only works for dynamic properties of a class instance and not declared class memebers (variables or methods). With ActionScript 1 and 2, delete could be used for anything. ActionScript 3 only lets you delete dynamic variables and locks those which are not.
ActionScript Code:

// ActionScript 2
class DeleteVarClass {
       
    public var myVar:Number;
   
    function DeleteVarClass() {
        myVar = 1;
        trace(myVar); // 1
        delete myVar;
        trace(myVar); // undefined
    }
}


ActionScript Code:

// ActionScript 3
package {
    public class DeleteVarClass {
       
        public var myVar:Number;
           
        public function DeleteVarClass() {
            myVar = 1;
            trace(myVar); // 1
            delete myVar;
            trace(myVar); // 1
        }
    }
}


Because myVar in the above example was declared as part of the class definition, it cannot be deleted using delete in ActionScript 3.

Since you cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory you should set your variable's value to null instead of deleting it.
ActionScript Code:

myVar = null;


If all variable references to an object are null, the GC will mark it for deletion and it will eventually be cleared from memory.

lunatic 06-28-2006 08:19 AM

*sigh* I wish I had your brain. :(

senocular 06-29-2006 11:54 AM

The Dictionary Class
 
The Dictionary class (flash.utils.Dictionary) in ActionScript 3 is a new addition to ActionScript. Dictionary objects exactly like generic Object objects aside from one thing: Dictionary objects can use any value as a property name or key as opposed to a string.

Generic objects in ActionScript use string keys (names) for property definitions. If a non-string value is used as a key, the key interpretation is the string representation of that value. Example:
ActionScript Code:

var obj:Object = new Object();
obj["name"] = 1; // string key "name"
obj[1] = 2; // key 1 (converted to "1")
obj[new Object()] = 3; // key new Object() converted to "[object Object]"

for (var prop:String in obj) {
     trace(prop); // traces: [object Object], 1, name
     trace(obj[prop]); // traces: 3, 2, 1
}


If you attempt to use different objects as keys in generic objects, what you'll get iare string conversions that match each other. That means that though you have used separate objects as keys, to the object container, its the same key and they will reference the same value.
ActionScript Code:

var a:Object = new Object();
var b:Object = new Object();

var obj:Object = new Object();
obj[a] = 1; // obj["[object Object]"] = 1;
obj[b] = 2; // obj["[object Object]"] = 2;

for (var prop:String in obj) {
     trace(prop); // traces: [object Object]
     trace(obj[prop]); // traces: 2
}



The Dictionary class is not restricted to this limitation. You can have any value as a key and that value will fully represent that key as opposed to the object using its string representation. So in the above example, if a Dictionary instance is used, you would have two separate keys, one for each object.
ActionScript Code:

import flash.utils.Dictionary;

var a:Object = new Object();
var b:Object = new Object();

var dict:Dictionary = new Dictionary();
dict[a] = 1; // dict[a] = 1;
dict[b] = 2; // dict[b] = 2;

for (var prop:* in dict) {
     trace(prop); // traces: [object Object], [object Object]
     trace(dict[prop]); // traces: 1, 2
}



Though you still get [object Object] in the trace, this is a result of the string conversion in the trace command; it is a unique object key in the Dictionary instance.

Note that prop here is typed as *. This is important as the keys in the dict object can be of any type. If you used String for prop's type, it would cast the a and b objects as Strings when finding them in the loop making prop "[object Object]" instead of actual references to a and b which they would need to be to correctly obtain the values 1 and 2 through dict. For generic objects, regardless of the type used for prop, you will always get a String.

FatalDisruption 06-29-2006 04:13 PM

What is the point, can't you just use a regular object? I guess I'm confused as to what it would be used for.

senocular 06-29-2006 04:50 PM

Quote:

Originally Posted by FatalDisruption
What is the point, can't you just use a regular object? I guess I'm confused as to what it would be used for.


You can look at the examples and see where they are different. Objects use string keys where Dictionaries use the objects themselves. This lets you essentially use objects as variable names which can be very useful in the right circumstances.

For example, consider having a bunch of "male" objects and a bunch of "female" objects, and eventually you have your objects get hitched and all get married. However, male and female objects dont have any internal property that lets you specify who their partner is, so instead you set up a reference table to let you access any female from a male or male from a female so reference[male] = female. Given any male, access it from the reference object and it returns the respective female and vise versa. Here's the thing, using normal objects, this won't work because any male or female you use as a key will be resolved as "[object Object]" and after assigning them all to your reference object, it only ends up with one value, "[object Object]" which has the value of the last male of female you assigned to it. Dictionaries, on the other hand, don't make that string conversion and would work for this.

I even used a dictionary in my coil gallery to allow me to reference sprites added to the coil display. Sprites added using addItem were used with another object with coil-specific properties which was used in how the sprite was displayed in the coil display itself. Using a dictionary object, I could quickly access that wrapper by using a reference to the sprite without the need to modify anything within the sprite itself.

mathew.er 06-29-2006 06:19 PM

Regarding a post you wrote earlier, I am a little curious about one thing... Why would anyone need * as a type? Isnt
ActionScript Code:

var anything:*;

the same as
ActionScript Code:

var anything:Object;

as everything comes from the Object class... Or are primitive data types not really objects?

FatalDisruption 06-29-2006 06:43 PM

I don't think Strings or Numbers etc are objects.


All times are GMT -7. The time now is 10:17 AM.

Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2006, Jelsoft Enterprises Ltd.
Copyright 2004 - kirupa.com