Dynamic code loading in ActionScript3

In my post regarding using PHP for Code Generation, Cyrus Lum asked the following question:

I was wondering about being able to load .as3 code snippets or classes at run time - Let’s say a user can download the swf, then through sockets, I can deliver a section of the code as a bytearray that would allow the swf to function.

This is definitely doable, though I’ve not done in exactly the way requested (via ByteArray via sockets). The Flex Framework provides a Module API that does exactly this, and if you Google around a bit you’ll find the Module API’s original author’s blog where he outlines his early experiments in building the API. Basically, you compile your “plugin” object as a stand-alone ActionScript project, producing an SWF. You then load that SWF with the Loader class (which accepts a URLRequest for the SWF, or a ByteArray for the bytes you pull from a socket). Once you have the SWF, you simply cast it to some known class and begin working with it.

The Module API has a Module class as the container for your plugin. Using MXML, the user creates a class that inherits from Module. The Module API loads the SWF and casts the object to a Module (which inherits from UIComponent, which inherits from Sprite, which is what any SWF that you compile from AS3 turns into). The Module API assumes your module is a component, so it places it on the stage somewhere, but you wouldn’t have to do that (thanks to the AS3 DisplayObject API).

3 Comments so far

  1. Ben Garney on September 26th, 2007

    Crazy timing - I just completed writing up (on my blog) how you do this under Tamarin, outside of Flex. JeffT pointed me your way. Small world!

  2. Troy on September 26th, 2007

    Your version is a bit more hardcore… ;-) We’re not loading ABC files or anything that nuts-n-bolts.

  3. Chetan Sachdev on January 22nd, 2008

    Hi,
    Is it possible to treat a swf created in Flash authoring tool (Flash CS 3) as a module?
    I have created some Shell/Module framework (ofcourse provided by Flex) my shell have some functionality say some Services, Commands etc. It provides a framework for game developers who can use our services. Please let me know, if it is not clear.

    Thanks

Leave a Reply