Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
haXe 2 Beginner's Guide

You're reading from  haXe 2 Beginner's Guide

Product type Book
Published in Jul 2011
Publisher
ISBN-13 9781849512565
Pages 288 pages
Edition 1st Edition
Languages

Table of Contents (21) Chapters

haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Getting to know haXe 2. Basic Syntax and Branching 3. Being Cross-platform with haXe 4. Understanding Types 5. The Dynamic Type and Properties 6. Using and Writing Interfaces, Typedefs, and Enums 7. Communication Between haXe Programs 8. Accessing Databases 9. Templating 10. Interfacing with the Target Platform 11. A Dynamic Website Using JavaScript 12. Creating a Game with haXe and Flash Pop Quiz Answers Index

Chapter 2. Basic Syntax and Branching

Basic constructs and making decisions.

In this chapter, we will learn about basic haXe constructs and pieces that make a program. We will also learn about branching (those are indeed constructs too), so that your program can make decisions and choose different paths according to conditions.

In fact, this chapter is one of the most important to get you started because it will teach you how to tell a haXe program what to do.

In this second chapter, we are going to learn quite a lot of things. The great thing is that after this chapter, you will have the knowledge to create programs that won't always do the same things. You will know about all haXe constructs too and therefore, should be able to have fun with haXe.

In this chapter, we will:

  • Learn about modules, packages, and classes

  • Learn about constants

  • Talk about binary and unary operators

  • Learn what blocks are and their particularities

  • Learn about variables and scope

  • Talk about how to access fields and call methods...

Modules, packages, and classes


If you're familiar with Object Oriented Programming (OOP) languages, then there are chances that you at least know the words "packages" and "classes"; if that's not the case, don't panic, you are going to learn all of it here.

Packages

Packages are a convenient way of splitting code into groups. Doing so, allows one to have several classes with the same name in different packages. This can be really useful, as you may, for example support two scripting languages in an application and need to write an interpreter class for each one.

Packages are represented by folders under your source directory on your filesystem. Each package has a path, which is a string obtained by joining the folders' name with dots. So, for example, if your source folder is /dev/myProject/src and you have a folder /dev/myProject/src/proj/dao, you have a package whose path is proj.da (you also have a package "proj"). There's a special package that has an empty path; it is named the top-level...

Constants and its types


There are six types of constants in haXe. We will now take a look at all of them. Some of them are composed of several kinds of them.

Booleans

The first type of constants is one that is spread most across programming languages: Booleans. For your information, in haXe Booleans have the type Bool. The following are two expressions, which are Boolean constants:

  1. true

  2. false

That's both easy and important. By the way, in haXe Bool is indeed an Enum (if you don't know what this is, don't worry, we will learn about it later). This Enum has two values, and true and false are just reference to these values.

Booleans are generally used to represent the truthiness of things. For example, when one is presented with a checkbox in an interface, the "checked" property of the checkbox can be of type Bool.

Integers

This one is easy; you can use integers constants by simply writing their values, for example:

  • 1234

  • -456

You can also use the hexadecimal notation by starting your value with...

Binary and unary operators


Binary and unary operators are two very important concepts in programming because they can both respectively be used to manipulate data. So, let's start with binary operators.

Binary operators

There are several operators, some of which you may already be familiar with, and some that you may not know, even if you have some programming experience. So, take a look at see all of them!

Assigning values

There are several operators that can assign a value to an expression:

Operator

Explanation

e1 = e2

Assigns the value of e2 to the expression e1. It returns the value of e2;

+= -+ *= /= %= &= |= ^= <<= >>= >>>=

Assigns the value to the expression on the left after performing the operation (see before). For example, a += 5; is equivalent to a = a + 5;. It will return the new value of the expression on the left.

Comparison operators

There are several comparison operators, all of them returning either true or false.

Blocks


Blocks are important things in haXe, as they can help you write things that might be complicated in some languages in an easy way. Blocks are delimited in the C-style by the { and } characters. What makes them special in haXe is that they have a value and a type. A block's value and type is those of the last expression of this block. Note that empty blocks are of Void type. This type is used to indicate that no value is going to be returned.

Here's an example on how that may ease writing in some cases:

public static function main() : Void
{
   var s : String;
   s = if(true)
      {
         "Vrai";
      } else
      {
         "Faux";
      }
   trace(s);
}

In this example, it will always trace Vrai (which is the French translation of "True"), but I think you get the idea. In most other languages, you would have to write something like:

public static function main() : Void
{
   var s : String;
   if(true)
      {
         s = "Vrai";
      } else
      {
         s = "Faux";
      ...

Variable declaration and scope


Understanding how variable declaration is done and its scope is very important.

Declaring a variable

You can declare a variable by using the var keyword followed by the name of the variable. There are two syntaxes to declare a variable: one is to declare variables at class level, and another one is to declare local variables in blocks of instructions (inside functions, for example).

At class level

The following is the syntax you can use to declare a variable at the class level:

[public|private] [static] var varName [: varType] [= someValue];

Note that if you don't specify public or private, all members will be private unless the class implements the Public interface.

Static variables are variables that will be stored directly inside the class and not inside the instance of the class (this does mean that there will be only one value for them in the whole program). A static variable can only be accessed through the class, not through its instances. By the way, unlike...

Time for action – Declaring some fields


Now, imagine that we want to create a class named Person. Its instances should have a public name field, a private age field, and the class should have a static and public count field.

  1. The first thing we can do is to write it in the following way:

    class Person
    {
       public var name : String; //This one is public
       var age : Int; //This one is private
       public static var count : Int = 0; //This one is static and initialized at 0
    }
  2. On the other hand, we can write it by implementing the Public interface, as follows:

    class Person implements Public
    {
       var name : String; //This one is public
       private var age : Int; //This one is private
       static var count : Int = 0; //And this one is public
    }

What just happened?

These two solutions will result in exactly the same thing:

  • Without implementing Public: When a class does not implement Public, all of its fields are private by default. That's why we have to explicitly write that the name and count properties...

Field access and function calls


Accessing fields and calling methods in haXe is quite easy. All fields of an object (that is all functions that are variables of this object) are accessed by using the dot notation. So, if you want to access the name variable of an object named user you can do so in the following way:

user.name

Calling a function is really easy too, all you have to do is put parentheses after the function's name and eventually write all of your arguments inside the parentheses, separated by commas. Here's how to call a function named sayHelloTo of an object named user, taking two strings as parameters:

user.sayHelloTo("Mr", "Benjamin");

That's all! It's quite easy, really.

Constructing class instance


Constructing a class instance is done using the new keyword, as follows:

var user = new User("Benjamin");

In this example, we create an instance of the User class. Doing so calls the class' constructor. The class constructor is defined in the class as the public non-static new function. It may take any number of parameters. The following is an example of our User class:

class User
{
   public function new(title : String, name : String)
   {
      //Do things
   }
}

You can call the superclass's constructor by calling super() (with parameters if needed).

You can access the current class instance using the this keyword.

Conditional branching


Conditional branching is a very important part of programming because it will allow your program to behave differently depending on the context. So, let's talk about if and switch.

If

The if expression allows you to test an expression; if it returns true then the following expression will be executed. You may also use the else keyword, followed by an expression, which will be executed if the test returns false. Note that a block of code is an expression.

The following is the general syntax:

if (condition) exprExecutedIfTrue [else exprExecutedIfTestFalse]

Now, let's look at some examples:

if(age<18)
{
   trace("you are not an adult.");
} else
{
   trace("You are an adult");
}

I think it is obvious here what this block of code does. Notice that this code could have been written in the following way too:

if(age<18)
   trace("you are not an adult.");
else
   trace("You are an adult");

This can be interesting to know, as it can save some typing when the block has only one...

Loops


Loops are one of the basic constructs in a language. So, let's see the loops that haXe supports.

While

While is a loop that is executed as long as a condition is true. It has the following two syntaxes:

while(condition) exprToBeExecuted;
doexprToBeExecuted while(condition);

With the first syntax, the condition is tested before entering the loop. That means, if the condition is not true, exprToBeExecuted will never be executed.

With the second syntax, the condition is tested after the execution of exprToBeExecuted. This way, you are sure that exprToBeExecuted will be executed at least once. The following are two simple examples to help you understand how these syntaxes have to be used:

public static function main()
{
   var i : Int = 0;
   while(i< 18)
   {
      trace(i); //Will trace numbers from 0 to 17 included
      i++;
   }
}

The preceding code is for the first syntax, and now, the second syntax:

public static function main()
{
   var i : Int = 0;
   do
   {
      trace(i); //Will...

Break and continue


break and continue are two keywords used inside loops.

Time for action – Using the break keyword


The break keyword allows one to exit a loop prematurely. Now, let's imagine that we have a loop that has 10 iterations, but we only want to go through the first eight ones.

Let's write a simple loop from 0 to 9 included. Note that we want to exit this loop as soon as we hit the 9th one.

for(i in 0...10)
{
   if(i==8)
   {
      break;
   }
   trace(i);
}

What just happened?

At the beginning of each loop, we test whether we are in the 9th one or not, if we are, then we exit the loop by executing break.

The result of this code will be:

TesthaXe.hx:12: 0

TesthaXe.hx:12: 1

TesthaXe.hx:12: 2

TesthaXe.hx:12: 3

TesthaXe.hx:12: 4

TesthaXe.hx:12: 5

TesthaXe.hx:12: 6

TesthaXe.hx:12: 7

Time for action – Using the continue keyword


Let's say that we want to display the number from 0 to 9 included, but not the number 8. We can use the continue keyword to do so, by directly going to the next iteration of our loop.

Let's write the following code that contains our loop, and a test done at each iteration to jump to the next iteration if needed:

for(i in 0...10)
{
   if(i==8)
   {
      continue;
   }
   trace(i);
}

What just happened?

In this Time for Action, we test if i is equal to 8, if it is, we simply go to the next iteration, therefore avoiding the printing of i.

This code will display the following:

TesthaXe.hx:12: 0

TesthaXe.hx:12: 1

TesthaXe.hx:12: 2

TesthaXe.hx:12: 3

TesthaXe.hx:12: 4

TesthaXe.hx:12: 5

TesthaXe.hx:12: 6

TesthaXe.hx:12: 7

TesthaXe.hx:12: 9

Return


The return keyword is used to exit from a function or to return a value from a function (and exit it).

function isAdult (age : Int) : Bool
{
   if(age < 18)
   {
      return false;
   }
   return true;
}

This is a function that should help you understand how to use the return keyword. It returns false if the age is inferior to 18, or else it returns true.

Exception handling


Exceptions are messages passed from the inner call of your program to the outer call (it is going through the stack from the most recent call to the older one). In haXe, any object can be thrown as an exception. Exception handling (that is intercepting those messages) is done with the help of the try and catch keywords.

try
{
   doSomething();
} catch (e : Int)
{
   //If do something throws an Int this block of code will be executed.
} catch (e : String)
{
   //If do something throws a String this block of code will be executed.
} catch (e : Dynamic)
{
   //If do something throws something else this block of code will be executed.
}

As you can see in this example, you can specify different types of exceptions to intercept and execute different blocks of code according to these types. The Dynamic type allows you to intercept any type of exception that hasn't been intercepted before. Mind the order in which you write your blocks, as they are evaluated from top to bottom...

Anonymous objects


Anonymous objects are objects that you create on the fly using brackets. The following is an example:

{ age : 12, name : "Benjamin" };

This object, despite not being created from any class, is typed. Its type is: {age :Int, name : String}.

The following is an example that you can run:

class TesthaXe
{
   public static function main(): Void
   {
      var user = {name : "Benjamin", age:12};
      neko.Lib.println("User " + user.name + " is " + user.age + " years old.");
   }
}

This program will print User Benjamin is 12 years old.

Local functions


Local functions are functions without a name. (often named "anonymous functions") They are values and as such can be assigned to any variable. The following is an example:

public class User
{
   var sayHello : String->Void;
   
   public function new()
   {
      sayHello =    function(to : String)
               {
                  trace("Hello" + to);   
               };
   }
}

Local functions can access any local variable declared in the same scope as static variables, but cannot access the this variable.

Local functions are typed. The local function in the preceding example is typed as String-> Void. A function that takes a String, an Int, and returns a String would be typed as String ->Int -> String.

So, continuing the previous example, one could call the function in the following way:

public class User
{
   var sayHello : String->Void;
   
   public function new()
   {
      sayHello =    function(to : String)
               {
                  trace("Hello...

Managing a fridge


This has been a pretty long chapter and we are now going to create something, which takes advantage of all that you have seen!

Time for action – Managing a fridge


We are going to create software to manage a fridge. We want to be able to add meals inside it, and to list what is in it. Ok, let's start!

  1. Create a folder that is going to hold your project's files.

  2. Create two folders inside it: a src folder and a bin folder.

  3. In your src folder, create a MyFridge folder. This way, we now have a MyFridge package.

  4. In the MyFridge package, create a Fridge.hx file with the following code inside it:

    package MyFridge;
    class Fridge
    {
       public static var meals = new List<Meals>();
    }
  5. This way, our fridge will hold a list of meals inside it. We can make this variable static because we will only have one fridge.

  6. Now, in the MyFridge package, create a file named Meal.hx and write the following code in it:

    package MyFridge;
    
    class Meal
    {
       public var name : String;
       
       public function new(f_name : String)
       {
          this.name = f_name;
       }
    }
  7. We now have a class Meal and its instances will have a name.

  8. We will now create a menu....

Summary


We learned a lot in this chapter about syntax.

Specifically, we covered how to declare classes and variables. We also covered how to iterate on lists and arrays, and how things are organized in haXe.

Don't worry, things will get easier now that we are done with the basics of the language.

lock icon The rest of the chapter is locked
You have been reading a chapter from
haXe 2 Beginner's Guide
Published in: Jul 2011 Publisher: ISBN-13: 9781849512565
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime}

Operator

Explanation

e1 =...