Memento Haxe

 0
 0
Estimated reading time:6 minutes 56 seconds

Voici une liste des différents codes source et syntaxes courante utilisées en Haxe.
Ce fichier est un canevas qui s'étoffera au fur et à mesure de mes expérimentations sur ce langage et son éco système .

Références/Sources:

Syntaxe de Base

  • package; // Package namespaces are organized by directory structure, supplemented with compiler options
  • exemple de script

    class HelloWorld {
    static public function main():Void {
    trace("Hello World");
    }
    }

Les variables et les types simples

  • exemple

    var an_integer:Int = 1;
    
    // You can also represent integers with hexadecimal:
    var hex_integer = 0xffffff;
    
    var x = 1;
    
    // The $type() method prints the type that the compiler assigns:
    $type(x);
    
    var an_interpolated_string = 'the value of x is $x';
    
    // Affichage dans la sortie standard
    trace(" Integer: " + 10 + " Float: " + 3.14 + " Boolean: " + true);
    trace(x + " is the value for an_integer");
    
    /* Strings are immutable, instance methods will return a copy of parts or all of the string.
    (See also the StringBuf class).
    */
    var a_sub_string = a_string.substr(0,4);
    trace(a_sub_string + " is the value for a_sub_string");
    
    /* Regexes are also supported, but there's not enough space to go into much detail. */
    var re = ~/foobar/;
    trace(re.match('foo') + " is the value for (~/foobar/.match('foo')))");

Les types complexes

  • les tableaux

    /* Arrays are zero-indexed, dynamic, and mutable.  Missing values are defined as null. */
    var a = new Array<String>(); // an array that contains Strings
    a[0] = 'foo';
    trace(a.length + " is the value for a.length");
    a[9] = 'bar';
    trace(a.length + " is the value for a.length (after modification)");
    trace(a[3] + " is the value for a[3]"); //null
    /* Arrays are *generic*, so you can indicate which values they contain with a type parameter: */
    var a2 = new Array<Int>(); // an array of Ints
    var a3 = new Array<Array<String>>(); // an Array of Arrays (of Strings).
  • les dictionnaires (ou listes)

    /* Maps are simple key/value data structures.  The key and the value can be of any type. */
    var m = new Map<String, Int>();  // The keys are strings, the values are Ints.
    m.set('foo', 4);
    // You can also use array notation;
    m['bar'] = 5;
    trace(m.exists('bar') + " is the value for m.exists('bar')");
    trace(m.get('bar') + " is the value for m.get('bar')");
    trace(m['bar'] + " is the value for m['bar']");
    
    var m2 =  ['foo' => 4, 'baz' => 6]; // Alternative map syntax
    trace(m2 + " is the value for m2");
    
    /* Remember, you can use type inference.  The Haxe compiler will decide the type of the variable
    the first time you pass an argument that sets a type parameter.
    */
    var m3 = new Map();
    m3.set(6, 'baz'); // m3 is now a Map<Int,String>
    trace(m3 + " is the value for m3");
  • les énumérations

    // A type with a limited number of states:
    enum SimpleEnum {
    Foo;
    Bar;
    Baz;
    }
    // you can specify the "full" name
    var e_explicit:SimpleEnum = SimpleEnum.Foo;
    // but inference will work as well.
    var e = Foo;
    switch(e){
    case Foo: trace("e was Foo");
    case Bar: trace("e was Bar");
    case Baz: trace("e was Baz"); // comment this line to throw an error.
    }
    
    // enumerate *constructors*
    enum ComplexEnum{
    IntEnum(i:Int);
    MultiEnum(i:Int, j:String, k:Float);
    SimpleEnumEnum(s:SimpleEnum);
    ComplexEnumEnum(c:ComplexEnum);
    }
    var e1:ComplexEnum = IntEnum(4); // specifying the enum parameter
    /* switch on the enum, as well as extract any parameters it might of had. */
    switch(e1){
    case IntEnum(x) : trace('$x was the parameter passed to e1');
    default: trace("Shouldn't be printed");
    }
    
    // another parameter here that is itself an enum... an enum enum?
    var e2 = SimpleEnumEnum(Foo);
    switch(e2){
    case SimpleEnumEnum(s): trace('$s was the parameter passed to e2');
    default: trace("Shouldn't be printed");
    }
    
    // enums all the way down
    var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3)));
    switch(e3){
    // You can look for certain nested enums by specifying them explicitly:
    case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : {
      trace('$i, $j, and $k were passed into this nested monster');
    }
    default: trace("Shouldn't be printed");
    }
  • Les conversions de types

    // string to integer
    Std.parseInt("0"); // returns 0
    Std.parseFloat("0.4"); // returns 0.4;
    
    // integer to string
    Std.string(0); // returns "0";
    // concatenation with strings will auto-convert to string.
    0 + "";  // returns "0";
    true + ""; // returns "true";

Les conditions et les boucles

  • condition simple

    // simple if
    var j = 10;
    if (j == 10){
    trace("this is printed");
    } else if (j > 10){
    trace("not greater than 10, so not printed");
    } else {
    trace("also not printed.");
    }
    
    // "ternary" if
    (j == 10) ?  trace("equals 10") : trace("not equals 10");
    
    // Switch statements
    switch(my_dog_name){
    case "fido" : favorite_thing = "bone";
    case "rex"  : favorite_thing = "shoe";
    case "spot" : favorite_thing = "tennis ball";
    default   : favorite_thing = "some unknown treat";
    // case _   : favorite_thing = "some unknown treat"; // same as default
    }
  • compilation conditionnelle

    #if neko
    trace('hello from neko');
    #elseif js
    trace('hello from js');
    #else
    trace('hello from another platform!');
    #end
  • boucles

    // while loop
    var k = 0;
    while(k < 100){
    // trace(counter); // will print out numbers 0-99
    k++;
    }
    
    // do-while loop
    var  l = 0;
    do{
    trace("do statement always runs at least once");
    } while (l > 0);
    
    // for loop
    var m = [1,2,3];
    for (val in m){
    trace(val + " is the value for val in the m array");
    }
    
    // iterate on an index using a range
    var n = ['foo', 'bar', 'baz'];
    for (val in 0...n.length){
    trace(val + " is the value for val (an index for n)");
    }
  • parcours de tableau

    var filtered_n = [for (val in n) if (val != "foo") val];
    trace(filtered_n + " is the value for filtered_n");
    
    var modified_n = [for (val in n) val += '!'];
    trace(modified_n + " is the value for modified_n");
    
    var filtered_and_modified_n = [for (val in n) if (val != "foo") val += "!"];
    trace(filtered_and_modified_n + " is the value for filtered_and_modified_n");

Les méthodes (fonctions)

  • exemple

    function sayHello(name:String = "Mark") {
    trace('Hello ${name}');
    }
    sayHello();
    sayHelloTo("Mark");

POO

Les classes

  • création de classe et d'interface

    /* A simple class to extend */
    class BarClass {
    var base_variable:Int;
    public function new(){
      base_variable = 4;
    }
    public static function acceptBarInstance(b:BarClass){
    }
    }
    
    /* A simple interface to implement */
    interface BarInterface{
    public function baseFunction(x:Int):String;
    }
    
    /* A "child class" */
    class FooClass extends BarClass implements BarInterface{
    public var public_any:Int; // public variables are accessible anywhere
    public var public_read (default, null): Int; // enable only public read
    public var public_write (null, default): Int; // or only public write
    public var property (get, set): Int; // use this style to enable getters/setters
    
    var _private:Int; // variables are private if they are not marked public
    
    // a public constructor
    public function new(arg:Int){
      // call the constructor of the parent object, since we extended BarClass:
      super();
    
      this.public_any = 0;
      this._private = arg;
    
    }
    
    // getter for _private
    function get_property() : Int {
      return _private;
    }
    
    // setter for _private
    function set_property(val:Int) : Int {
      _private = val;
      return val;
    }
    
    // special function that is called whenever an instance is cast to a string.
    public function toString(){
      return _private + " with toString() method!";
    }
    
    // this class needs to have this function defined, since it implements
    // the BarInterface interface.
    public function baseFunction(x: Int) : String{
      // convert the int to string automatically
      return x + " was passed into baseFunction!";
    }
    }
  • instantiation et accès

    /* Create an instance of FooClass.  The classes for this are at the end of the file. */
    var foo_instance = new FooClass(3);
    
    // read the public variable normally
    trace(foo_instance.public_any + " is the value for foo_instance.public_any");
    
    // we can read this variable
    trace(foo_instance.public_read + " is the value for foo_instance.public_read");

Les extensions (moteur de jeu, framework, librairie...)

KHA

Références

setup complets

Memento de code

OpenFL

HaxeFlixel

IDEs

Visual studio Code (VS Code)

Kode Studio

  • un fork de visual studio code pré-configuré et optimisé pour le développement avec Kha (contient déjà "Kha Extension Pack"), contient quelques limitations (simplifications) des fonctionnalités de VS code
  • Site officiel

JetBrain Intellij Idea (et autres IDEs jetBrain)

Previous Post Next Post