background preloader

HaXe, un language universel orienté web

Facebook Twitter

Présentation du Langage HAXE | Delfiweb - Ressources Flash, Fram. Cet article a pour but de vous présenter le langage de programmation HAXE. Quel est donc ce nouveau langage ? Quel sont ses fonctionnalités ? Présentation logo haxe HaXe se présente comme un langage universel orienté web, c’est un langage multi-forme. Il permet de générer côté client des fichier Flash et du Javascript, et côté serveur un langage spécifique, Neko et tout récemment du PHP. Sur le serveur, Neko peut générer du bytecode qui tournera au dessus d’un module Apache, ou être compilé. Plusieurs projets basés sur le langage ont déjà vu le jour: HaXe se présente comme le successeur du fameux compilateur AS2, à savoir MTASC (compilation ultra rapide). Détails HaXe (AS3, AS2) est un langage supportant le développement par design pattern (IOC, MVC..). Il est possible de développer toutes les classes flash (avec l’éditeur FDT) puis de créer un swf contenant uniquement du code.

Puis le swf principal (contenant uniquement le code) se charge d’assembler le tout. Coté client Fonctionnalités. HaXe - Téléchargements. HaXe. HaXe - Références. HaXe - Types Basiques. Haxe syntax is similar to Java, ActionScript and C++. A source code file is composed of an optional package name followed by imports and type declarations. Package names look like this: haxe.long.package.name. Type identifiers look like this: SomeGenericIdentifier. There are several kinds of types. The two most important ones are classes and enums. Enum Void { } class Float { } class Int extends Float { } enum Bool { true; false; } enum Dynamic<T> { } Here's a quick description of each type. Void is declared as an enum. Syntax »» HaXe - La Syntaxe.

In Haxe, all statements are expressions, which means they can be nested. For example, foo(if (x == 3) 5 else 8) is valid Haxe. As this example shows, every expression returns a value of a given type. Here are some examples of constants in Haxe: 0; -134; 0xFF00; 123.0; .14179; 13e50; -1e-99; "hello"; "hello \"world\" ! "; 'hello "world" ! '; true; false; null; ~/[a-z]+/i; Notice that null has a special value, since any value can be null.

The following operations can be used, in order of priority: Unary operations (see next section below).e1 % e2 : calculates e1 modulo e2, Return Int if they were both Int, otherwise return Float.e1 / e2 : divide two numbers. Note: Associativity of operators can be found here here The following unary operations are available : ! Note: ~ is usually used for 32-bit integers, so it is incompatible with Neko's 31-bits integers. Surrounding an expression with parenthesis will give that expression higher priority when it is to be evaluated.

. { e1; e2; eX; } o.field. HaXe - L'Inférence de type. Haxe can determine the type of a variable based on the value assigned to that variable. This feature, known as type inference, means you receive all the benefits of strong typing without needing to explicitly define the type of each variable. For example, the following code: var f = 10.5; var s = "foo"; var arr = ["hello", "world"]; will be compiled as if you had written: var f : Float = 10.5; var s : String = "foo"; var arr : Array<String> = ["hello", "world"]; If you'd like to know which type the compiler inferred at compile time you can use the special identifier '$type'. This can be useful when debugging. We'll use '$type' in the rest of this document to demonstrate how the compiler infers types.

Anywhere in your program, you can use the $type operation to know the type of a given expression. Var x : Int = $type(0); This will print the line number together with 'Warning : Int' at compilation, and still compile the same program as if $type was not used. Drawing from the first example: HaXe - La Programmation Orientée Objet. We will quickly introduce the structure of classes that you might already be familiar with if you've done some OO programming before : package my.pack; class MyClass { } A Class can have several variables and methods. All class variables must be declared with a type (you can use Dynamic if you don't know which type to use).

Function arguments and return types are optional but are still strictly checked as we will see when introducing type inference.Non-static variables may not have an initial value. Variables and methods can have the following flags : The class can optionally specify a static intiailizer function to be run before any other aspects of the class are initialized. Static function __init__() { ...; } This function will be run when the application first starts up, before any static member variables of the class have been initialized.

The class can have only one constructor, which is the not-static function called new. Constructor parametrization & overloading : Extends Implements. HaXe - Les Paramètres de type. A class can have several type parameters that can be used to get extensible behavior. For example, the Array class has one type parameter: Inside the Array class, the type T is abstract which means its fields and methods are not accessible. However when you declare an array you need to specify its type : Array<Int> or Array<String> for example. This will act the same as if you had replaced all types T in the Array declaration by the type you're specifying. The type parameter is very useful in order to get strict typing of containers such as Array, List, and Tree. While it's nice to be able to define abstract parameters, it is also possible to define several constraints on them in order to be able to use them in the class implementation.

In this class, although the field evt is a class paramater, the typer knows that it has both types Event and EventDispatcher so it can actually access it like if it was implementing both classes. «« Object Oriented Programming - Enums »» HaXe - Les énumérations. Enums are different from classes and are declared with a finite number of constructors. Here's a small example: When you want to ensure that only a fixed number of values are used then enums are the best thing since they guarantee that other values cannot be constructed.

The previous Color sample shows three constant constructors for an enum. It is also possible to have parameters for constructors : This way, there is an infinite number of Color2's possible, but there are five different constructors possible for it. The following values are all Color2: Red; Green; Blue; Grey(0); Grey(128); Rgb( 0x00, 0x12, 0x23 ); Rgb( 0xFF, 0xAA, 0xBB ); We can also have a recursive type, for example to add alpha : The following are valid Color3 values : Alpha( 127, Red ); Alpha( 255, Rgb(0,0,0) ); Note that enums are immutable, which means the parameters of an Enum are read-only. A switch has a special behavior when used on an enum. An Enum can also have type parameters. HaXe - Les Paquets et Importations. Each file can contain several classes, enums and imports. They are all part of the package declared at the beginning of the file.

If package is not declared then the default empty package is used. Each type has then a path corresponding to the package name followed by the type name. package my.pack; enum E { } class C { } This file declares two types : my.pack.E and my.pack.C. It's possible to have several classes in the same file, but the type name must be unique in the whole application, so conflicts can appear if you're not using packages enough (this does not mean that you have to use long packages names everywhere). When creating types using packages, you should create a nested folder/directory structure matching the package name, and your files defining the type should be created in the innermost folder/directory. The file extension for Haxe is .hx.

Imports can be used to have access to all the types of a file without needing to specify the package name. Say we have: Or, equivalently: HaXe - Le type Dynamic. Disclaimer: Dynamic variables are often necessary to ensure interoperability with third party or platform dependent libraries, or for very specific cases where dynamic variables are absolutely required. Their use is not encouraged for normal use, as their behavior differs between targets.

When you want to get some dynamically typed behavior and break free from the type system, you can use the Dynamic type which can be used in place of any type without any compile-time type-checking: var x : Dynamic = ""; x = true; x = 1.744; x = {}; x.foo = 'bar'; x = new Array(); When a variable is marked "Dynamic" the compiler does not ensure that types are followed for a given variable. At run time however, different targets may not recognize or even allow certain operations on certain variables. Var x:Dynamic = 4; x.foo = "Bar"; //flash9: ReferenceError: Error #1056: Cannot create property foo on Number. An untyped variable is of type Unknown and not Dynamic. Parameterized Dynamic Variables or Untyped. HaXe - Les Types avancés. Up to now, we have seen the following types : class instanceenum instancedynamic There are several additional important types.

A structure type is the type of an anonymously declared object. It is also the type of a Class identifier (corresponding to all the static fields) or an Enum identifier (listing all the constructors). Here's an example that shows it: You can define type definitions which are a kind of type shortcut that can be used to give a name to a structure type or a long type that you don't want to repeat everywhere in your program : The same code can also be written as: typedef PointCube = Array<Array<Array<Point>>> Typedefs are not classes, they are only used for typing. As aliases You can "alias" types using type definitions in the following manner: class MyClassWithVeryLongName { }typedef MyClass = MyClassWithVeryLongName; You can assign any kind of type like this, not just classes - enums, interfaces and other type definitions can be aliased as well in the similiar manner. HaXe - Les Itérateurs. An iterator is an object which follows the Iterator typedef (The type T is the iterated type) : You can use the for syntax in order to execute iterators.

The simplest iterator is the IntIter iterator which can easily be built using the operator ... (three dots). For example this will list all numbers from 0 to 9 : for( i in 0...10 ) { } Or the usual for loop : for( i in 0...arr.length ) { foo(arr[i]); } You don't need to declare the variable i before using a for, since it will be automatically declared. You can also define you own iterators. Once your iterator is implemented, you can simply use it with the for...in syntax, this way : var iter = new IntIter(0,10); for( i in iter ) { } The variable name in the for is automatically declared and its type is bound to the iterator type. If an object has a method iterator() taking no arguments and returning an Iterator type, it is said to be iterable. Var a : Array<String> = ["hello","world","I","love","Haxe","! "] HaXe - Les Propriétés. Properties are a specific way to declare class fields, and can be used to implement several kinds of features such as read-only/write-only fields or fields accessed through getter-setter methods.

Here's a property declaration example : The values for get and set can be one of the following : a get or set keywords, which means the corresponding method must exist (in our example these are "get_x" and "set_x" functions)null if the access is restricted from anywhere but its class' methods (see more below)default if the access is a classic field accessdynamic if the access is done through a runtime-generated methodnever if the access is never allowed, not even by means of Reflection Here's a complete example: Using property declarations, we declare five public fields in the class C : For instance, the following two functions are equivalent, although the methods get_x and set_x are private and then can't be accessed directly as in f2 : var c : Dynamic = new C(); trace(c.x);

HaXe - Les Arguments optionnels. Some function parameters can be made optional by using a question mark before the parameter name or by providing a default value. Providing a default value simply makes the parameter optional. Explicitly adding a question mark also implies nullability When not specified, an optional parameter will have the default value null. It's also possible to define another default value, by using the following syntax : static function foo( x:Int, y:Int=5, z:String="hello" ) { } Thanks to type inference, you can also shorten the syntax to the following : static function foo( x:Int, y=5, z="hello" ) { } When not specified, an optional parameter will have the default value null but on static platforms (Flash, CPP, Java, C#) null can't be used as basic type.

Static function foo( ? Will be compiled as: static function foo( ? Considering the following function: static function foo( x=1 ) { it cannot be called with foo(null); unless you add a question mark : static function foo( ? Or add type information: HaXe - Compilation conditionelle. HaXe - L'instruction inline. The inline keyword can be used in two ways: for static variables and for any kind of method. For static variables, it's pretty simple. Every time the variable is used, its value will be used instead of the variable access. Example : class Test { static inline var WIDTH = 500; static function main() { trace(WIDTH); }} Using "inline" adds a few restrictions : the variable must be initialized when declaredthe variable value cannot be modified The main advantage of using "inline" is that you can use as many variables as you want without slowing down your code with these variables accesses since the value is directly replaced in the compiled/generated code.

The principle is the same for a method. Let's have a look at one example : Again, there's some limitations to inline functions : Apart from these few restrictions, using inline increases the compiled/generated codesize but brings a lot of additional speed for small methods. «« Conditional Compilation. Commencer avec haXe/JS. Developing Javascript code is really easy with Haxe. Let's see our first HelloWorld example : class Test { static function main() { trace("Hello World ! "); }} Put this class into a file named Test.hx and create the file compile.hxml in the same directory with the following content : -js test.js -main Test To compile, you can simply double-click on the compile.hxml file (or run the command haxe compile.hxml). <html><head><title>Haxe JS</title></head><body><div id="haxe:trace"></div><script type="text/javascript" src="test.js"></script></body></html> If you put this code into a file named test.html and open it with your webbrowser, it should display Hello World with information about the file and the line where the trace occured.

This example does not cover package often used to help organise the classes in your project. Another possibility to display some text is to use alert. Compile and open the test.html. Watch the available APIs from Lib . Tutoriaux JavaScript. Utilisation d'AJAX. Commencer avec haXe/Flash. Tutoriaux Flash. Commencer avec haXe/Neko. Commencer avec HaXe / PHP. Tutoriaux PHP. Catégorie HaXe sur Delfiweb. HaXe - API.

DOM, XML, JSON