Haxe and AS2

We’re starting to use Haxe in Silex, and it fell to me to start porting the core from as2 to Haxe. We’ve decided to do it progressively, so that means getting as2 and Haxe code to work together in the same SWF. This post will therefore go through the different steps to take to get these two languages to be able to instanciate and use objects in the other.

  • getting the two to compile together: compile your as2 as you would normally. We use mtasc, but this should also work with Flash CSx. Then compile your Haxe project using the -swf-lib compiler option. This tells the Haxe compiler to include an existing swf as a library.

  • instanciating as2 classes from Haxe: If you try to use the as2 class as you would a Haxe class, the compiler will stop you. But don’t worry, it’s there, you just have to tell the compiler to let you access it. This is where you use the new keyword.  This is stuff you shouldn’t normally use unless you know what you’re doing, but in this case it’s the only way.  So supposing you have a class in as2 called As2Class. Here is how to use it in Haxe: var as2Class = untyped new(As2Class);

One final gotcha is to make sure your as2 class is included by the compiler. An import is not enough, it has to be instanciated at least once somewhere in your as2 code.

  • instanciating Haxe classes from as2.

This is more complicated. as2 classes are in _global. But Haxe classes are in _root. Furthermore, you have to wait for the first frame to be able to use them.  It seems that in Haxe an import is enough to make sure a class is included. It does not necessarily need to be instanciated by your Haxe code, contrarily to as2.

Here is a sample main function, as called by mtasc as the entry point to your project:

//_root.HxClass is undefined here

trace(“main _root.HxClass: “ + _root.HxClass);

// entry point

swfRoot.onEnterFrame = function() {

//_root.HxClass should be available here

trace(**“_root.onEnterFrame _root.HxClass
“** + _root.HxClass);

var hxClass = new _root.HxClass();

_root.onEnterFrame = null;

}

}

Here is a zip containing the two Flash Develop projects and the source. Compile the as2 project first.

testhaxe

Rejoignez nous