We have been working on a new website which went live today: the Haxe Code Cookbook. It has categorized code snippets with additional explanations; small code tutorials and examples in a central place.
There is also a GitHub repository. The website is powered by pull requests so it is easy to add new content. Everyone with a GitHub account can contribute by putting markdown formatted files in one of the category-folders we’ve created, or suggest a new one. The site is generated with Haxe (of course) and with an automatic process (using Travis) new snippets will go live immediately after being reviewed.
We hope this will grow into a useful central world with Haxe coding snippets and tutorials!
The FlashDevelop Team and the Haxe Foundation have joined forces to release a Haxe-specific version of FlashDevelop: HaxeDevelop. HaxeDevelop offers first class support for Haxe development: great and fast code completion & code generation, refactoring, projects compilation, debugging, plenty of project templates, etc.
This blogpost is about making bitwise operations in Haxe more easy. If you like doing micro optimization in your code, you probably want to use bitwise operations. But I found the main problem about bitwise operations is that they are hard to read. If you know the syntax and know what it does it might be “doable”, but if you work in a team it might get harder if not everyone is familiar with the syntax.
A common example of using bitwise operators is to put multiple states into one integer. Some call them flags.
For example, lets say you want to build a app where users have different rights to view a document. You could create a User class with multiple booleans like this:
class User {
public var name:String;
// user rights
public var CAN_VIEW:Bool = true;
public var CAN_ACCESS:Bool = true;
public var CAN_EDIT:Bool = false;
public var CAN_GRANT_ACCESS:Bool = false;
public var CAN_REVOKE_ACCESS:Bool = false;
public var CAN_DELETE:Bool = true;
}
But if you want to optimize it, you could also put all those values into an variable. Computers deal with ones and zeros right?
class User {
public var name:String;
// user rights
public var rights:String = "000001";
}
In this case we create a string with zeros and ones. We could say that the last value means “can view” and the one next to it “can access” etc.. In our case only the last digit is “1” so that means it is on (true). the others are “0” so they are false.
Understanding bitwise operations
Well, this could work, but working with numbers in strings is not very elegant, and also not practical. And it’s awkward when you want to add another flag to it. Why don’t we just use a number for that? That’s where bitwise operations come in. Let’s put it in an integer:
class User {
public var name:String;
// user rights
public var rights:Int = 0;
}
Given the last explanations, we can say:
CAN_VIEW == 000001
CAN_ACCESS == 000010
That would mean that:
CAN_ACCESS and CAN_VIEW == 000011
When we translate it to code it would be:
1 | 2 == 3
For those who can count binary, 000011 in real value equals 3. By the way, the leading zero’s don’t mean anything.
Ok, let’s move on and define all our flags. Define a new class that has all the access flags in it like this:
class Access {
public static inline var CAN_VIEW:Int = 1;
public static inline var CAN_ACCESS:Int = 2;
public static inline var CAN_EDIT:Int = 4;
public static inline var CAN_GRANT_ACCESS:Int = 8;
public static inline var CAN_REVOKE_ACCESS:Int = 16;
public static inline var CAN_DELETE:Int = 32;
}
As you see the order is: 1, 2, 4, 8, 16, 32 (and if we go further 64, 128, 256, 512 etc etc..) This means when 1 | 2 == 3, we can now do:
var user = new User();
user.rights = Access.CAN_VIEW | Access.CAN_ACCESS;
trace(user.rights); // 3
Play with this live-example to see how you can blend different flags.
Nice! now we know how to mix and blend different rights to the user. Let’s say you want to make somebody admin you can do this:
To go back on how we declared the Access class, I think it can be improved. It now has that count that is slightly annoying since it doesn’t feel natural. Let’s look at this table.
Real value
Binary
Left shifted
1
000001
1 << 0
2
000010
1 << 1
4
000100
1 << 2
8
001000
1 << 3
16
010000
1 << 4
32
100000
1 << 5
As you notice in the last column, the same values can be achieved with a left shift <<. So “000001” equals “1” but is the same when we write it like “1 << 0”. Personally I think its more readable to have this last column in your code because it just increases normally, what do you think?
Nicer syntax with Haxe enum abstract
Let’s use the power of Haxe to simplify the Access class. Instead of using static vars, let’s create an enum abstract.
enum abstract Access(Int) from Int to Int {
var CAN_VIEW = 1;
var CAN_ACCESS = 2;
var CAN_EDIT = 4;
var CAN_GRANT_ACCESS = 8;
var CAN_REVOKE_ACCESS = 16;
var CAN_DELETE = 32;
}
But wait, let’s also use the left shift so we don’t have to count those 1,2,4,8 etc..
enum abstract Access(Int) from Int to Int {
var CAN_VIEW = 1 << 0;
var CAN_ACCESS = 1 << 1;
var CAN_EDIT = 1 << 2;
var CAN_GRANT_ACCESS = 1 << 3;
var CAN_REVOKE_ACCESS = 1 << 4;
var CAN_DELETE = 1 << 5;
}
That looks a bit friendlier because if you now want to add another field, you can just add “1 << 6” and “1 << 7“. But hey this post was about readability right? Why not create a simple function so we can get rid of this “1 << ” thingy? Yep, we can! 😀
enum abstract Access(Int) from Int to Int {
var CAN_VIEW = value(0);
var CAN_ACCESS = value(1);
var CAN_EDIT = value(2);
var CAN_GRANT_ACCESS = value(3);
var CAN_REVOKE_ACCESS = value(4);
var CAN_DELETE = value(5);
static inline function value(index:Int) return 1 << index;
}
Ah, in my opinion everybody can maintain this. Even if you don’t understand what’s happening. Since we use the ‘inline’ there is no actual function call in the output. You can see in this live-example how the generated output looks like. Neat! Now, that’s it for the Access class.
We created an actual type!
Hey! Since Access is now an actual type, we can even define user.right as follows:
public var rights:Access; // isn't this nice!?
But it still translates and actually works as an integer when it is compiled.
Working with bitsets in Haxe
Let’s go back to the user.rights field. What if we want to remove a flag? The syntax for that would be:
user.rights = user.rights & ~Access.CAN_EDIT;
😯 Aiiii, there goes our readability isn’t it? Well lets create a utility class that contains a remove function. I use this BitSets class from Flambe, which has some other nice functions too (like testing if a integer contains a flag).
class BitSets {
inline public static function remove (bits:Int, mask:Int):Int {
return bits & ~mask;
}
inline public static function add(bits:Int, mask:Int):Int {
return bits | mask;
}
inline public static function contains (bits :Int, mask :Int) :Bool {
return bits & mask != 0;
}
}
With the above, we can now use this much more readable code:
// add flags
user.rights = user.rights.add(Access.CAN_EDIT).add(Access.CAN_ACCESS);
// remove flags
user.rights = user.rights.remove(Access.CAN_EDIT);
// check if flag exist
if (user.rights.contains(Access.CAN_ACCESS)) {
trace("can access");
}
With Haxe, you could also leave out the enum class (if it’s imported or a class inside your module), so we can write:
// add flags
user.rights = user.rights.add(CAN_EDIT).add(CAN_ACCESS);
// remove flags
user.rights = user.rights.remove(CAN_EDIT);
// check if flag exist
if (user.rights.contains(CAN_ACCESS)) {
trace("can access");
}
It doesn’t get cleaner than that. Check out this full live-example to see how it all comes together and what the effect is on the generated output.
Conclusion
We saved ourselves from multiple booleans on a user class, we’ve learned how to use flags.
We made a enum abstract type called Access for our user.rights property.
I’m really proud of our latest Google ChromeCast game: Tricky Titans. It is a turn-based local multiplayer game in which you and up to four of your friends are pit against one another until a victor is decided.
The app is created with Unity, the actual game on ChromeCast is build with Haxe + Flambe. We created this game to build a showcase for the new Google GameManager SDK.
Download Tricky Titans
Now available free for iPhone, iPad and Android. iOS | Android
If you also want to build a game with Haxe for the ChromeCast, I’ve open-source the Cast SDK extern classes that are useful to work with the JavaScript SDKs.
This post is about grabbing conditional compilation values and print them in the output context using a macro function. Then we can use it at runtime.
Let’s say you want to display in runtime if your code is compiled in debug or release mode. You could do this, using conditional compilation tags: var debug = #if debug “debug” #else “release” #end; trace(‘This application is $debug build.’);
This is (maybe) good enough if there are two values, but in other cases where there are multiple values it will not work. A conditional compilation define can hold a value. Example: you can compile -D my_value=3 or -D my_value="nice". By default the Haxe compiler version is provided like this. The following works, but it looks messy and is not really maintainable: var haxeCompilerVersion = #if (haxe_ver == “3.2”) “3.2” #elseif (haxe_ver == “3.1”) “3.1” #else “aarrggh I don’t know all the versions” #end; trace(‘This application is build using haxe $haxeCompilerVersion’);
To make a function that works for both cases, we write a macro function that grabs a define value and returns it as expression of a String. public static macro function getDefine(key:String, defaultValue:String = null):Expr { var value = haxe.macro.Context.definedValue(key); if (value == null) value = defaultValue; return macro $v{value}; }
What’s happening here? The Context.definedValue provides us every conditional compilation value. We can grab the key we’re looking for, and return them as value expression for the ouput context. In case a value isn’t defined, a “fallback” value is used (defaultValue).
This allows us to grab all these values out of the box: var debugValue = MacroUtils.getDefine(“debug”, “release”); var haxeVersion = MacroUtils.getDefine(“haxe_ver”); var deadCodeElimination = MacroUtils.getDefine(“dce”);
Of course, when we compile the application with a custom define like -D target=mobile or -D target=web, you can use MacroUtils.getDefine('target') in your code too.
It has been almost a year, but these week the Haxe Foundation released a massive new version of the Haxe Cross-platform Toolkit: Haxe 3.2 These are some of the new features I’d like to highlight:
Introduction of a new compiler target: Python
Added static analyzer with constant propagation. This leads to even more smaller and cleaner code! use -D analyzer to activate it
try.haxe.org uses 3.2 now too, and you can test this new analyzer.
Also the Haxe manual has new content and getting more complete.
Haxe has become a solid language/toolkit for developers. Today it has more than 11.000+ commits on Github from a high skilled team with 70 contributors. This release again demonstrates the power and potential of a language that serves as the solution for cross-platform development.
I’m using Haxe for almost 2 year on daily basis, I’m really enjoying using it. It’s open-source, free and complete to do whatever you want on whatever platform 🙂
I did some contributions to http://try.haxe.org/ lately. This is a nice tool that allows you to write, compile, test and share Haxe code online. It runs the latest release version of Haxe.
There is a new tab called ’embed’ after you hit ‘compile + run’ [html] <iframe src=”http://try.haxe.org/embed/ea9da” frameborder=”0″ width=”100%” height=”300″ style=”border:1px solid #333; box-shadow:0 0 5px #F48821;”></iframe> [/html] That will create this nice sharable widget:
Btw, note how awesome switch statement that is.
Enjoy writing code, now start share your knowledge with the world! Wow, thanks!