Hey everyone! This post is dedicated to a feature that’s very important to me when writing Haxe code and that’s externs. You’re going to learn how to write them yourself to make your life easier when combining your Haxe code with existing libraries. With that said, let’s breakdown what externs are.
What Are Externs
Using & Creating Externs
You create an extern in Haxe by creating a new extern class file. It’s very similar to a regular Haxe file. The important thing is that you use the extern keyword to tell Haxe that it’s external code you’re working on. You don’t have to write the implementation details; you are just calling what already exists in your codebase.
Externs also support all of the standard Haxe modifier keywords such as public, private, static, and so on. Use them to make sure the code matches your own implementation details. For example, if you call your function in JS like this:
This is how you would write the function on the Haxe side.
public static function create(x?:Float, y?:Float):Point;
Simple right? Let’s look at an example for a Point class below.
Here’s how you do it; here’s an example extern class with some tips to make your life easier. This is one we use in our own game engine framework LunaTea.
As you can see, the most important things are the extern keyword at the top of the class and the native metatag. This should match up with what you previously wrote in JS. The native tag also helps you deal with reserved keywords in your target language by allowing you to rename the function or method, or even make special versions of a method. The “code” is the definition similar to C; it’s just a signature telling Haxe what to expect when we call it in our Haxe code. The output in JS would match exactly what you call it in JS.
See externs are pretty straight forward. Don’t be intimidated by the code!
With that said, hope this helps and good luck with your own code!