February 2010

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

# ActionScript 3 Language Syntax Cheatsheet

Feb 2010

I started my Flash learning from reading about the ActionScript 3 language syntax from the "Learning ACTIONSCRIPT 3.0". Here is my quick-and-dirty sketch of a language syntax cheatsheet. I assume you are already familiar with programming in C++ and/or Java, so I emphasize differences.

Some background: ActionScript language comes from ECMAScript, which means it has syntax very similar to JavaScript, which in turn resembles C++ or Java. It's a case-sensitive language. It significantly evolved from version 1 through 2 until 3. It started as very dynamic, scripting-like language with dynamic data types and prototype-based object model (like in JavaScript or Lua). But now it looks more "serious" with the ability to define classes and compilation-time type checking (more like in C++ or Java).

Ending statements with semicolon ; is optional in ActionScript. Comments look exactly like in C++ - we have single line comments after // and multiline ones between /* and */. We also have many control statements looking just like in C++ - if, switch, while, do-while, return, break, for, continue. Interestingly, we can but labels into code like in C++ and then reference them in break and continue.

There are exceptions available, so we can use try-catch-finally blocks and throw exceptions like this:

throw new Error("Invalid email address");

Source code consists of packages with classes inside them, like:

package MyPackage1 {
  public class MyClass1 {

There can be only one public class inside a source file (default file extension is .as) and it has to have same name as the file name.

There can also be raw code (any statements, e.g. function calls) outside function definitions, like inside a class, a package or even at the top level. They are executed at program start.

Here is how you define variables (local variables or class fields):

var i1:int;
var s1:String = "abc";
var x:Number = 1, y:Number = 2.5;

You can also define constants:

const MyConst1:uint = 0xDEADC0DE;

Scoping rules for variables are similar to C++, so you can have static and normal class fields, as well as method parameters and local variables inside methods. There is a difference that {} blocks inside code do not create nested naming scope.

Primitive intrinsic data types are:

Complex intrinsic data types are: Array, XML, XMLList, Date, Function, RegExp, Object. Variables of these types are always passed and assigned by reference. Of course there is no manual memory management, the language has a garbage collector.

Variables are automatically initialized with default values. For int and uint it's 0, for Number it's NaN (!), for Boolean it's false, for Object and String it's null.

Here is how you define functions (methods). The example below is an event handler - events are widely used in Flash. There is an event for MOUSE_DOWN, MOUSE_MOVE, as well as ENTER_FRAME - called every frame, for example 30 times per second (sounds familiar? :)

private function OnMouseMove(event:MouseEvent):void

Default parameter values are supported, just like in C++ (and opposite to C#). There is also a rest operator ... available to enable passing any number of arguments.

Available attributes for classes are: internal (the default), public, dynamic (methods and properties can be added in runtime - see below), final (cannot be inherited). Attributes for class members are: internal (default), private, protected, public, static or a namespace name (see below).

Calling constructor of a base class can be done with super() keyword. If not explicitly called, the constructor of the base class is automatically called at the beginning of our constructor.

Methods do not need to be explicitly declared as virtual, but overriding them in subclasses requires override keyword. Method can also be declared as final so it cannot be overriden.

Because classes are organized inside packages, we have to either qualify them with full path like flash.events.MouseEvent, or import them into global namespace with:

import flash.events.*; // Importing everything from this package
import flash.events.MouseEvent; // Importing single class

When it comes to operators, we have whole bunch of standard arithmetic, logical and bitwise operators available similar to C++ or Java:

String concatenation is + which is quite intuitive, but not so obvious (as PHP use dot . for this purpose and Lua uses double dot ..). Object-oriented operators are also available (as in every modern and comfortable language - C++ is not one of them :P), like "is" and "as". Operator "as" returns null if cast is not possible.

Explicit type casting is done this way: Int(myString1). These are actually global functions, not type casting operators. Casting string to a numeric type does parsing so characters are converted to number. Strings with numbers saved in hexadecimal form like "0x123F" are also supported. Casting Boolean to String returns "true" or "false". Casting String to Boolean returns false if string is null or empty "".

ActionScript supports interfaces. Thay are like classes, but have to use "interface" keyword instead of "class" and have some restrictions. Class inheritance is done with the "extends" keyword and subclassing interfaces with "implements" keyword.

ActionScript provides very nice syntax for declaring so called getters and setters - class properties that work like methods, but can be used like fields. Here is an example:

private var privateProperty:String;
public function get publicAccess():String {
  return privateProperty;
public function set publicAccess(setValue:String):void {
  privateProperty = setValue;

Enums have not explicit support in ActionScript. One should declare a class instead with static constants of type uint, String or any other.

public final class PrintJobOrientation
  public static const LANDSCAPE:String = "landscape";
  public static const PORTRAIT:String = "portrait";

Function in ActionScript is a type, so functions can be assigned to variables, passed and returned. They are closures, which means they remember the context from which they come, including local variables (for nested functions) or object properties (for class methods extracted from objects). Example:

var traceParameter:Function = function (aParam:String) { trace(aParam); }

Arrays can be initialized with [] parentheses, like:

var seasons:Array = ["spring", "summer", "autumn", "winter"];

Basic text printing to the debug output can be done with trace function, e.g.:

for (var i:uint = 0; i < 10; i++)

There are also two loop instructions to iterate over array elements or dynamic object properties. The for-in loop iterates over keys in array or property names in object:

var myObj:Object = {x:20, y:30};
for (var i:String in myObj)
  trace(i + ": " + myObj[i]);

The for-each loop iterates over values in array or property values in an object:

var myObj:Object = {x:20, y:30};
for each (var num:int in myObj)

The example above also shows dynamic object with arbitrary properties put inside during construction with {} operator. You can also dynamically add and delete properties of an existing object, like:

myObj.z = 10;
myObj['z'] = 10;
delete myObj.z;

To use your own class this way, you have to define it with dynamic keyword.

There is another dynamic feature still existent in ActionScript 3 - untyped (dynamically typed) variables. They are defined with asterisk * instead of type name.

var dynVar:*;
dynVar = 10;
dynVar = "Foo";

ActionScript has special syntax support for regular expressions with / operator, e.g.:

var myRegExp:RegExp = /foo-\d+/i; 
trace(myRegExp.exec("ABC Foo-32 def.")); // Foo-32

It looks very crazy for me that ActionScript accepts XML embedded just inside the code like an intrinsic type.

var employee:XML =

XML nodes can be addressed intuitively like in XPath, because language supports XML operators: @ . .. {} [] delete. For example:

var myXML:XML = <item id="42">
  <catalogName>Presta tube</catalogName>
trace(myXML.@id); // 42

Files (e.g. graphics or sound) can be embedded into classes with so called embedded asset classes, as in the example:

[Embed(source="sound1.mp3")] public var soundCls:Class;
public function SoundAssetExample()
  var mySound:SoundAsset = new soundCls() as SoundAsset;
  var sndChannel:SoundChannel = mySound.play();

Packages in ActionScript work like namespaces in C++, but ActionScript also have namespaces. They do something completely different though and they are the most crazy thing I can see in the syntax of this language. They are the way to define your own class member visibility specifiers next to standard keywords like public, private, protected and internal. For example:

class Class1 {
  public namespace Namespace1;
  public function Method1():void { }
  Namespace1 function Method2():void { }

Comments | #flash Share

# Learning ActionScript - TestProject02

Feb 2010

So I now learn ActionScript 3 in my free time at home. I think such technology is worth knowing as it has many adventages - the language is easy so I turn my ideas into code very fast, as well as present them online so you don't have to download and run any real application to see it working. Of course it's not a high-performance 3D technology and I always feel a bit limited when I code in a language with no fast, direct access to raw memory bytes through pointers, but it's sufficient for many purposes. As I learn it, I have lots of ideas about how could I use it to create some interesting graphics or gamelay experiments, presentations (e.g. for learning and understanding some geometry math) or even entire games. And from all these online technologies like Java or JavaScript + AJAX, I think I prefer Flash the most.

How exactly do I learn it? First of all, there is this big and expensive Flash with graphical design environment, but I don't use it. I use pure ActionScript 3 programming language (the version is very important here) and FlashDevelop - a great IDE for Windows that looks fast and lightweight but is very convenient and powerful at the same time (I wish IntelliSense in Visual C++ worked like this).

I've been looking for a tutorial to learn the language, but I haven't found anything that would satisfy me, so I've downloaded official documentation from Flash CS3 resources. Until now I've read "Learning ACTIONSCRIPT 3.0" (there is a PDF version for download) and of course I always have the Language Reference opened (there is a downloadable version ActionScriptLangRefV3.zip as ZIP with multipage HTML inside).

Here is my first application - Conway's Game of Life. Use left mouse button to interact.

You can download the entire FlashDevelop project here: TestProject02.zip or see the main script online: Main.as.

Comments | #flash Share

# SVN in My Windows Made Me Angry

Feb 2010

Today I had an unpleasant adventure with SVN. Although I'm now going to use Mercurial (with TortoiseHG client) for my home projects, as this whole distributed revision control systems looks quite promising, I wanted to checkout some SVN repository and it turned out to be much bigger problem than I expected.

The obvious solution is to install and use TortoiseSVN - great shell extension for Windows. Unfortunately it doesn't work in my 64-bit Windows 7. Setup succeeds, but then no new items appear in context menus for directories. I tried to install both 64-bit and 32-bit versions, two times, with restarting my computer. Nothing helped. I tried to disable read-only attribute for TortoiseSVN directory, give full permission to this directory for all users, maually run TSVNCache.exe (because it doesn't start automatically) and nothing helped. I also ensured shell extensions are successfully installed by using ShellExView. Google knows this problems, but not the solution.

So then I installed RapidSVN - a normal Windows SVN client. Such application seems even nicer for me than shell extension. But then another obstacle appeared: opening repository in RapidSVN failed with error message: rapidsvn Error: Error while updating filelist (Can't create tunnel: The system cannot find the file specified. ). I though: Fuuuu! After issues with new Windows version here come Linux-like issues with some command-line or config driven, small and independent programs that never smoothly work together. I knew it was probably because the repository I wanted to checkout have an URL starting with svn+ssh:// so the SVN client probably needs to create an SSH tunnel.

After some searching in Google I found a solution. I needed to download PuTTY package and set special environmental variable to point to the plink.exe program that, according to Google, work as SSH tunnel. This variable is named "SVN_SSH" and its value must be like "E:\\PuTTY\\plink.exe" - without quotes, but with these double backslashes! Here I was sure it had to come from the Linux/Unix world, noone other would come up with something like this :P

It seemed to work so I was a step further, but still I couldn't access the SVN repository. This time when checking out, an empty console appeared and freezed so the RapidSVN didn't go any further. I wanted to try some "easy" solution so I installed another windowed client - Qsvn, as well as console SVN client - SilkSVN, but it seemed to recognize and run this SSH tunnel and finally freeze in same situation. So after another Googling I've found this post, opened configuration file "C:\Users\MY_LOGIN\Application Data\Subversion\config" and inserted this line into it:


It finally worked and I could access the repository, but it took me so much time that it made me really angry. I hope I'll live to see the day when there will be no such stupid problems with software. Meanwhile, now you can understand why do I always *very* carefully handle all errors in my code (check returned values, throw exceptions, write logs) - to always know exactly what, when, where and why went wrong, so no annoying things can happen like "context menu items don't show up and I don't know why" or "empty console window opens and freezes".

Comments | #svn #windows #software #tools #version control Share

# RegEngine - Design

Feb 2010

I'm now starting coding new game engine. It's called RegEngine. Here is a general design. It's coded in C++ for Windows. This time it will be general game engine, not only renderer. Also, this time I'm going to create an editor (I've never done this before).

I will use wxWidgets 2.9 as GUI library for the editor. It's not an obvious choice though. For example, C++/CLI (which I use at work) is also nice technology as it allows to freely mix native and managed code so one can create GUI with Windows Forms while coding the rest in native C++. But personally I prefer something that is fully native. Qt is also good, looks more mature, stable and, well, "serious" than wxWidgets and it's also free for some time. But wxWidgets is more lightweight than Qt (to a certain degree, as GUI library can be). It also looks like wxWidgets is the only GUI library that has both docking and property grid control built in. (I'm talking about version 2.9 here, because stable 2.8 version of wx doesn't have the property grid yet.)

I want to separate engine from renderer. But I'm not going to make an abstraction to be able to transparently switch between DirectX and OpenGL as it makes no sense for me. I just want to have the ability to use my engine, with all its functionality like scenes, actors, scripts, AI, sound etc. with new renderer I would code some day, let it be DirectX 11 or software one. To do this, my engine will be component based. An actor standing in the scene will just have its name and/or some ID, position, bounding volume and a set of components. If it's visible, its rendering component will be an object from the renderer.

There is also a great idea I want to incorporate into my engine that I know from Krzysiek K. (greetings!). It goes like this: The game, which will be a document for the editor (that's what you can create as New, Open, Save, Save As etc.) is a single, big tree of objects of different type. This tree includes both resources (like textures, meshes, sounds) and scenes with hierarchies of actors inside them, as well as any other entities (like dialogs in an RPG game). Object can have sub-objects and can also have a set of properties of different types (like bool, int, float, string, vector, matrix, color). Framework for these properties (I'll call it "reflection") will automatically serialize them to/from file, show them in property grid in the editor and hopefully make them visible to scripts. This whole idea gives consistent framework to store, serialize and edit all game data.

As creating new dialog boxes is not my favourite activity (no matter if it's coding or clicking :) I've been thinking for a long time about the "ultimate" set of general controls necessary to make a game editor. I currently think that it's sufficient to have:

Some not so necessary and more difficult to code controls are:

RegEngine will consist of modules compiled as static libraries:

First screenshot:

Comments | #engine #RegEngine Share

# I Recommend Mass Effect 2

Feb 2010

In the past week I bought, played and finished Mass Effect 2 (on PC) and I want to strongly recommend this game. It's really great. I generally like RPG games. I also played and finished first version of Mass Effect and liked it.

Version 2 is much better though. Graphics is better, more detailed. They've removed all the annoying things like long elevator travels or driving "Mako" on the planet surfaces. They've introduced some nice minigames instead - gathering resources from the planets (quite boring but I liked it), hacking electronic circuits and hacking code (which are great ideas). As a main gameplay, they've taken all what's best in modern RPGs (like lots of talking, hard moral choices, nonlinear story, personal history and problems of characters) and shooters (like cover system, aiming, boss fights). Game is quite long (it took me 9 days to finish it), but as for RPG it's an adventage.

As a summary, I strongly recommend Mass Effect 2 to anyone who likes RPGs and/or shooters. I can't remember when I played any game so passionately since The Witcher, and I played dozens of great of games since then. I'm glad I'm not the only one who thinks Mass Effect 2 is great - professional reviews and sales indicate it's generally very successful.

Comments | #games #shopping Share

[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2020