Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
haXe 2 Beginner's Guide
haXe 2 Beginner's Guide

haXe 2 Beginner's Guide: Develop exciting applications with this multi-platform programming language

eBook
Can$12.99 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

haXe 2 Beginner's Guide

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.

Operator

Explanation

e1 =...

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.

Left arrow icon Right arrow icon

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2011
Length: 288 pages
Edition :
Language : English
ISBN-13 : 9781849512572
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 26, 2011
Length: 288 pages
Edition :
Language : English
ISBN-13 : 9781849512572
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 166.97
Haxe Game Development Essentials
Can$34.99
haXe 2 Beginner's Guide
Can$61.99
OpenGL 4.0 Shading Language Cookbook
Can$69.99
Total Can$ 166.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Getting to know haXe Chevron down icon Chevron up icon
Basic Syntax and Branching Chevron down icon Chevron up icon
Being Cross-platform with haXe Chevron down icon Chevron up icon
Understanding Types Chevron down icon Chevron up icon
The Dynamic Type and Properties Chevron down icon Chevron up icon
Using and Writing Interfaces, Typedefs, and Enums Chevron down icon Chevron up icon
Communication Between haXe Programs Chevron down icon Chevron up icon
Accessing Databases Chevron down icon Chevron up icon
Templating Chevron down icon Chevron up icon
Interfacing with the Target Platform Chevron down icon Chevron up icon
A Dynamic Website Using JavaScript Chevron down icon Chevron up icon
Creating a Game with haXe and Flash Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(3 Ratings)
5 star 33.3%
4 star 33.3%
3 star 33.3%
2 star 0%
1 star 0%
Lars Mathiasen Feb 06, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
razaina Sep 11, 2011
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
It's about 2 years I'm using haXe. I'm not a beginner but I still have constantly a lot of stuff to learn.haXe is a powerful language which provides many features, and gives to developers a tool to create websites, and applications. Thanks to its cross-platform features, it brings ease to target different platforms using a single unified programming language.In this book, Benjamin Dasnois made a great job of introducing the specifics of the language.The book is really easy to read, and at first sight, it is aimed for beginners, but not only because I was surprised to learn stuff I never tried to do before, and to reinforce my knowledges in some area like how different applications can communicate between each other (Chapter 7 : Communication between haXe programs).The chapters of the book are cleverly well structured.The "Time for action" heading followed by the "What just happened ?" make this book so enjoyable to read.Like a recipe, you just have to follow instructions and then you can ta(e)ste it. The second heading gives clear explanations about how tasks or instructions work.The only negative for this book to me is that C++ which is a haXe target that I didn't experimented yet, isn't covered, so I expected to read some stuff about it.If you're looking for a comprehensive introduction to what haXe is all about, or if you're a beginner or an intermediate haXe developer who want to fill gaps in your knowledge, I really would recommend buying this book.Anyway, subscribe to the haXe mailing list and stay tuned for all the new features the language is offering.
Amazon Verified review Amazon
Amazon Customer Oct 26, 2011
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Writing a book about haxe seems to me extremely difficult because of the language multi platform nature, constant improvement process and a variety of projects related to the haxe. And I'm glad that Benjamin Dasnois started this great work of collection knowledge about haxe in a book format. This is the first edition and certainly there are a number of things I would suggest to improve.My main complaint is to extreme brevity. Of course a small size is good for a book, but text often doesn't explain why things are so as they are, only enlists strict facts about the language without discussion, gets you know about alternatives or providing a list of advantages and disadvantages. OOP concepts definitions from my point of view are currently poor and I'm sure that it should be said in preface that a reader must be familiar with at least one OOP language to follow the author's ideas easily.The other thing I was very disappointed about is a low quality of the code snippets. Examples contain dead code, number of compile errors, absence of single code style and bad indentation. Also almost everywhere in the book single line comments spread across several lines and that produces errors after copying code into a text editor. As a result there's a strong feeling of incompleteness and mediocrity. Hope it will be corrected as soon as possible.In my opinion there are still enough unexposed places in the book without further references (e.g. how I can make types comparable, what is the range of integer, performance discussion and targets nuances). Some links to the documentation or even well-known discussions in mailing lists would be very useful if it is not possible to include that information into the book.There are several things I would recommend to add to this book. A full description of haxe compiler options because it's not clear how to work with the given examples. More steps how to setup environment for running examples for those who is unfamiliar with described target platform. Also I think that there should be more explanation and some comparisons with other languages to know why one should prefer haxe instead of using them. A fair description of current haXe problems and their possible solutions could enclose a useful chapter. And surely I should mention that book doesn't consider C++ target and has no information about macroses.On the other hand I was glad to get know about templates and SPOD library in haXe and will definitely try to play with them closer. There is a good chapter how to feel comfortable in the community that is very important for haxe beginners.On the whole "haXe 2 Beginner's Guide" in current version is an overview of some haXe possibilities. It could be useful for those who is familiar with OOP concepts and wants to see main features of haxe without a lot of details but with some examples.[...]
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.