This is a beginner's tutorial on using the Haxe programming language.
For a general introduction on Haxe visit http://haxe.org/doc/intro.
To get started with writing programs in Haxe, you need to setup Haxe on your computer. Download the installer for your platform from this page.
We are using the automatic installer for windows. Install it by running as administrator.
How to write a program in Haxe?
In order to program in Haxe, you will need two files:
- .hx file: which has the main class containg the entry point of the program.
- .hxml file: it contains the compiler options.
You can use a text editor of your choice. Flash develop is a good free and open source option. It has built-in support for Haxe code completion.
This tutorial will target Haxe to the Flash platform.
The .hx file: It contains the main class “Test”.
Name the file as “Test.hx”.
package;
import flash.Lib;
import flash.display.Sprite;
/**
* ...
* @author Qoncious.com
*
*/
class Test extends Sprite
{
private var _array:Array<Int>;
private var _sum:Int;
public function new () // new() is the constructor
{
super();
_array = [1, 10, 2, 5, 90, 60];
_sum = 0;
for (i in 0 ... _array.length) // observe the for loop
{
_sum += _array[i];
}
trace("Sum of the contents of the array: " + _array.toString() + " is equal to " + _sum);
}
/**
* the function main() is called first when swf starts
* flash.Lib.current is the main swf MovieClip. So here we are adding an instance of the Test class to the main MovieClip.
*/
static function main()
{
Lib.current.addChild(new Test());
}
}
The .hxml file:
Name the file as “compile.hxml”. Write the following code inside it.
-swf test.swf
-main Test
It tells the compiler to create a test.swf using the main class Test.
Keep the two files in the same directory or folder.
Complie the .hx file using the .hxml file:
In windows you can double-click on the .hxml file or right-click and select compile. If it did not compile, right-click on the file > Open with > Choose default program … > Browse... to haxe.exe. You can find haxe.exe at “C:\HaxeToolkit\haxe”.
You can also compile it from the command prompt:
Open command prompt, change the working directory to the directory containing the Test.hx and compile.hxml files. Use the command “haxe compile.hxml”.
If everything goes fine, a test.swf file will be generated in the same diectory. You can open the swf file using any modern browser with Flash plugin enabled.
The output test.swf file displaying the text.