Introduction
A few months ago, it was announced that the popular MTASC open source compiler will get a new version that will compile a new language called haXe. The haXe compiler 1.0 has been released for a few days now on the http://haxe.org website, so it may be a good time to have a look at how it can help you to create Flash content.
What is haXe ?
haXe is a programming language that can be used to develop Flash content, but not ONLY flash content. Imagine writing ActionScript for both front and back-end : Flash, JavaScript and Server-side. That's the kind of unified programming language haXe offers. Learning and using haXe is easy for the Flash/ActionScript developper. Yet it offers some powerful features that will increase code quality, reusability and maintainability. haXe provides an extensible standard library that directly provides standard tools commonly used by developers.
haXe is a crossplatform programming language. It means that the haXe language can be used to develop for the following different plaforms :
- The Flash Platform : haXe can be used to develop Flash/SWF content and can target Flash Players 6,7,8 and soon 9. Porting code from ActionScript 2 to haXe is very easy, and it's possible to interact between AS2 and haXe. Everything that you can do with AS2, you can also do with haXe.
- The Javascript/AJAX platform : haXe can be used to develop the Javascript/AJAX part of your website. Since haXe is a strongly typed language, it reduces the number of typos. The haXe standard library provides cross-browser compatibility.
- The Server-side/Neko platform : haXe can be used to develop the Server-side of your website, with database and filesystem access. haXe is generating code for the
mod_neko Apache module which is a stable and very fast virtual machine.
haXe provides the ActionScript developer the option of writing in a common language among all of these aspects of a web application. The haXe standard library offers capabilities for crossplatform communications and integration with other languages/technologies. Best of all, you can choose the parts of haXe that fits your project. It is already a great tool for Flash-only or Server-only development, as well as a unified standard for web application development.
Hello World
We will now quickly see how to get started with a Hello World Flash sample. First download the haXe distribution from http://haxe.org/download and unzip it somewhere on your drive. Execute the haxesetup.exe that will setup the compiler.
You can now create your first haXe class :
// Hello.hx
class Hello {
static function main() {
trace("Hello World !");
}
}
To compile this example, you need to run the haXe compiler. It's a commandline compiler that can be easily integrated in any IDE. But instead of running the compiler from the commandline, we will create an haXe project file using the HXML format :
# Hello.hxml
-main Hello
-swf hello.swf
The HXML file is simply a list of haXe compiler commandline parameters that are listed one-per-line. The advantage is that you don't have to rewrite the commandline parameters all the time, and that on Windows you can simply double-click on the HXML file to compile your project.
We will do that now : double-clicking on the HXML will open a console window and start compilation. It's very fast and there is no errors so the window is automatically closed and a file hello.swf has been created. In the case there are errors in your code, the window will not close so you can read the displayed errors.
When opening the hello.swf file by double-clicking on it or embedding it into an HTML page, we can see the text displayed on the Flash clip. Please notice that when we call trace, it will also display the filename and linenumber where the trace was done (in our sample Hello.hx:4). This is really helpful for quickly debugging.
Using the Library
We saw how haXe can display some text, but we don't know yet how to use the Flash API and the Library. Let's start another sample that will display a MovieClip at the center of the Stage and rotate it every frame :
// Rotate.hx
class Rotate {
static var mc : flash.MovieClip;
static function main() {
mc = flash.Lib._root.attachMovie("myclip","myclip",0);
if( mc == null )
trace("myclip is not in the library");
mc._x = flash.Stage.width / 2;
mc._y = flash.Stage.height / 2;
mc.onEnterFrame = loop;
}
static function loop() {
mc._rotation += 3;
}
}
While most of the code is the same, we can see some small differences between haXe and ActionScript 2 :
- We use
flash.Lib._root instead of _root : this is because haXe is a pure OO language with no toplevel variables or methods (except trace). All AS2 toplevel functions and variables are then accessible as flash.Lib static methods and fields.
- Flash classes such as
MovieClip and Stage are in the flash package : this way standard classes available on all platforms such as Array or Date are separated from flash-specific classes.
Back to the sample, let's see how we compile it. For that, we will use an HXML file similar to the previous one :
# Rotate.hxml
-main Rotate
-swf rotate.swf
-swf-lib library.swf
-swf-header 400:400:30:8080FF
There is two new parameters :
-swf-lib will use the library stored in library.swf. In our sample, we are attaching the myclip library symbol. You need then to create this symbol with the Flash IDE and publish the FLA as library.swf.
-swf-header will specify the SWF properties (width:height:fps:bgcolor). In our sample, we are building a 400x400 SWF at 30 fps with a light blue background color.
Once your library.swf is ready, you can run the HXML file that will compile the code and add the library to build the file rotate.swf. Open it and you should see your myclip symbol rotating at the center of the stage.
Some haXe Features
Now that we have seen how you can use the Flash API from haXe (just like you would do with ActionScript 2), let's delve into the additional features provided by haXe for the Flash programmer.
Delegates
haXe as delegates built-in to the language, so when you write the following, the haXe compiler will automatically create a delegate :
mc.onRelease = obj.eventOnRelease;
With this feature, you no longer need to worry about which context your method is executed in.
Trace and Debug
We have seen that the trace function can be used to quickly display debug informations on the screen. More complex tracing can be achieved by rebinding the haxe.Log.trace method with your own display function. The --no-traces commandline parameter can also be used to remove all trace calls from compiled code.
Conditional Compilation
Sometimes it is needed to compile the code with a different configuration. For example a debug version and a release version can have different behavior, do more loggin or give more access to the system. While such configuration can be controled by some global flags, they can be easily modified by a smart user.
Conditional compilation is a way to compile different code depending on compilation flags. For example :
function startApplication() {
#if debug
// directly login
doLogin("myuser","mypassword");
#else true
displayLoginForm();
#end
}
The password will be readable in the SWF, but only if you compile with -D debug. When you make a release, compile without the flag to turn off all the special code you added when debugging your application. You can use as many flags as you need.
With the new Flash9 API available in ActionScript3, you will be able to use conditional compilation. This way, you will be able to compile for Flash Player 6 to 9, while using new Flash9 features and speed when compiling for FP9.
Type inference
In ActionScript, in order to get a strictly typed program, you need to write types everywhere, and in particular for each local variable :
var x : Number = 0;
var s : String = "hello";
var a : Array = [1,2,3];
var r : Boolean = obj.foo();
In haXe, each variable type is automatically inferred by the compiler :
var x = 0; // will be Int
var s = "hello"; // will be String
var a = [1,2,3]; // will be Array<Int>
var r = obj.foo(); // will be Bool since we know the type of 'obj'
While type inference reduces the amount of code you have to write, it also leads to better code since you are not preventing the compiler typechecks when you don't specify a variable type.
Dynamic / Untyped
While type inference is a powerful haXe feature that permits more strictly typed code, it's sometimes useful to write dynamicly-typed code. The special type Dynamic is here for that :
var v : Dynamic = 0;
v = "hello";
v(null);
var x : Int = v;
...
Once a type is Dynamic, you can use it as you wish. Please note that this is an explicit behavior of the haXe language : you have to declare when you want to write dynamic code since it's better to have strictly typed code by default.
You can also enclose some code into an untyped block to have all the code inside act as Dynamic :
untyped {
var v = 0;
v = "hello";
v(null);
}
Strictly-typed Arrays
Onc of the most commonly used data structures in Flash is Array. But it gives you no security about which type is contained by the array. haXe introduces generics which is a way to describe the Array content type :
var a = new Array<String>();
a.push("hello");
a.push("world !");
a.push(33); // compile-time error !
var x = a[0]; // x will be 'String'
var y : String = a[1]; // ok also
var z : Bool = a[1]; // compile-time error !
Strictly typed arrays are a very powerful feature that will increase your application safety. Please note that you can still create mixed-content arrays by using Array<Dynamic>. Strictly-typed arrays can also be combined with type-inference :
var a = ["a","b","c"];
a.push("hello");
a.push(33); // compile-time error !
var b = new Array();
b.push(11); // will turn b into an Array<Int>
b.push("bad"); // compile-time error !
Iterators
Arrays are a very common data structure in Flash because of the power of looping through them to iterate through its values :
// AS2
for(var i = 0; i < arr.length; i++)
doSomething(arr[i]);
// haXe
for( x in arr )
doSomething(x);
The for...in haXe loop is dedicated to iterable structures (such as array, list, hashtable, resultset...). You can make your own data structure iterable by implemeting the iterator() method.
Conclusion
So far we have introduced the haXe language, shown some very basic Flash samples, explained the differences between haXe and ActionScript 2, and introduced some of the exciting features provided by the haXe language for Flash developers.
There is still a lot to say about haXe, in particular how to develop complete websites with haXe, access databases and write AJAX code. All theses will be interesting subjects for further haXe articles.
With the 1.0 release, haXe has been growing very quickly and is now very stable. There are still some shortcomings due to haXe being so recently released, like no IDE fully supporting haXe, no native UI framework (although you can use existing AS2 ones) and Flash9 compilation not yet possible, but all of these should be soon available.
New features are available on a regular basis and the haXe community increases every day, with enthousiastic developers joining the mailing list, learning haXe and helping with its development by providing feedback and fresh ideas.
Why not you ? Visit http://haxe.org to download and start writing haXe code.