dave seah: better living through new media Filter Navigation Temporary Redirect Page Personal Articles Productivity Articles Compact Calendar The Printable CEO Series The Printable CEO Series Back to Home Page Admin:Login

Viewing Category: Programming

Flash Tools: MTASC Notes

POSTED 04/24/2006 UNDER FlashProgramming

Ben Jackson has been telling me to switch to alternative Flash Actionscript tools like MTASC, but I've been resistant. Today, however, I've gotten a little fed up with the sluggishness of the built-in Flash 8 compiler. The tradeoff: I like the Flash IDE, because it's comfortable and I like editing graphics within the environment. Plus, since I'm working on a PC, the experience doesn't have the tradition of sucking as it has on the poor Mac platform (though this has since been fixed in Flash 8...yay!)

Anyway, MTASC is much faster and more robust, but it is a command line tool with a different workflow compared to the Flash IDE. Time to do some research!

Warning: geeky notes follow, covering what it took to convert from Flash IDE to MTASC-friendliness. Ben already has a Mac writeup, so I'll be focusing only on Windows.

MTASC Installation Basics

On Windows, it's pretty simple to install:

  1. Go to mtasc.org and download the pre-compiled windows binary. It's a ZIP archive.

  2. Unzip the archive, and copy the resulting folder to someplace where you will keep it permanently. I have a dev folder in my d: drive, so it's in d:devmtasc.

  3. Since I'm running MTASC initially in a command-line environment, I have to add the MTASC directory to my path, so I can run it from any directory I'm working in. NOTE: This isn't a strictly-necessary step; I describe the batch file later that allows you to just double-click.

    However, if you are a command-line commando, do this: right-click the My Computer icon, choose Properties, then click the Advanced tab. Then click Environment Variables. You'll then edit the PATH System variable. I added d:devmtasc; to the end of the existing settings. You might want to first COPY the path value first and paste it into a text file...just in case you mess it up and create all sorts of problems for yourself. Yes, it's that important.

  4. Next, test that your path is set-up correctly by going to the Windows Start Button and choose Run... from the menu. Type cmd into the box: this is what will pull up your command-line shell. To test that you've set the MTASC path correctly, type mtasc and see if you get a help listing. If you instead see the error message mtasc is not recognized as an internal or external command, operable program or batch file, then you haven't set your path correctly. Double check that the path is correct, and that you edited the system variable in the previous step correctly.

BTW, if you Hate the Windows Command Line Shell...

When it comes to command line interfaces, I prefer more unix-like shells. So I downloaded UnixKit and am using that instead of the Windows cmd. The main advantage is that I can type ls instead of dir, and this makes me happy. Incidentally, UnixKit doesn't actually install anything, so you can easily move it from computer to computer on a flash memory drive and bring a unix-y environment with you when you travel. Yay!

Ok, back to MTASC.

MTASC Conceptual Hurdles

MTASC is an Actionscript 2.0 compiler, pure and simple. This means it doesn't do several things that we take for granted in the traditional Flash authoring environment:

  • MTASC doesn't know how to create any graphics assets at all, and it doesn't understand .FLA files. Therefore, you must import graphics assets from a .SWF file during the compilation process. So you'll still need Flash to create library assets. Alternatively, you can use something like SWFMill; I should look into it, but haven't yet.

  • Since MTASC an Actionscript 2.0 compiler, it doesn't digest legacy coding conventions very well. And the way my Flash movies in the past have started up is by putting an #include on frame 1 of the .FLA file. This was fine back in the day, and still works within the Macromedia Flash environment, but it will not fly with MTASC. There's another way to do it.

  • Since MTASC exists outside of the Flash environment, you will also need to set classpaths. You're used to doing that already with Flash's "Actionscript 2.0 Settings", so you just need to know how to set them when compiling with MTASC.

To convert my existing simple Actionscript 2.0 application (maybe a dozen of my own classes, plus Alex Uhlmann's AnimationPackage), I had to address all these issues.

Clarifying MTASC Command Line Usage

I was confused initially by what I thought was an ass-backwards compilation process. The usage notes states this on the main MTASC page:

MTASC takes the SWF file specified with the -swf flag, compile all .as specified files, and update the SWF file by replacing all classes that are present inside it by the newly compiled classes.

To use MTASC instead of Macromedia Flash Compiler, it's simple. Open your project and publish it normally (for example project.swf). Now run MTASC using the published SWF as input : mtasc (your as files) -swf project.swf. This will compile your classes and update the SWF that you can use for your website. Please note that MTASC add the compiled classes to the SWF in replacement of ALL classes compiled by Flash.

That sounded like to use MTASC, I had to first compile with Flash to create a SWF, then compile again??? What? The first time I read that, I completely lost interest and continued to use the Flash IDE. However, today I read a little further in the tutorial:

The only thing you need to do in order to run the sample is to call MTASC with the following arguments :

    mtasc -swf tuto.swf -main -header 800:600:20 Tuto.as

A hah...all that stuff about "compiling your source files with Flash first" isn't necessary...it's only if you want to, for some reason, use MTASC to recompile your SWF movie after you, uh, have already compiled it. You have the option of specifying a new entry point and generating a new SWF. That's the piece I was missing.

Speculation on usefulness of the other way:

  • It's possible that MTASC produces more optimal bytecode than the Macromedia compiler, and therefore produces faster code. That would be the traditional reason for switching compilers in the first place, but as the 'compiled' code is actually interpreted bytecode, I don't think this is the case...however, I haven't looked into this at all.

  • It's also useful if you want to do stricter source code checking on your existing source, as the Macromedia compiler is a little more forgiving and at times flaky.

  • UPDATE: After thinking about this, it actually does make sense if you already have your .SWF set up and are doing incremental changes...you just need a stub class and can recompile into the existing .SWF. It just seemed counter-intuitive based on my past command-line compiler experiences (admittedly, a bit limited).

Reorganizing your Flash Project for MTASC

Conceptually, this is how I broke down my Flash project to make it MTASC-compatible:

  1. Designate or create a class that will be your "startup class". Mine is called Application.

  2. Get rid of any initialization script code on the Timeline. You're coding in pure Actionscript 2.0 now, even more than you were before, so we must say goodbye to our hybrid scripting techniques; that includes using #include statements in Frame 1 of your Timeline. You will move your initialization code to the startup class, in a static method called main in a class of your choosing. For me, that's my Application class.

  3. After you move all your initialization code to the main() static method of your start up class, test that it still works in Flash. I nuked everything out of my frame 1 script and replaced it with a call to Application.main().

  4. If you're using any graphic assets in the library programmatically through the use of linkages, you still need Flash to create the .SWF file. The SWF will be imported into MTASC using a command-line option (more on that later).

Running MTASC from the Command Line

After I checked that the application was working within Flash, I was ready to run MTASC. As with any command-line compilation process, we need to know a few things up front:

  • The classpath of our Actionscript 2.0 .as source files

  • The path to the "startup class" Actionscript 2.0 file.

  • The path to the graphic assets .SWF file.

  • The path to any supporting classes, if they aren't in the same package structure of our application. For example, I keep animationpackage in d:devanimpackage, which is outside the classpath of my test project. We'll be entering this information into MTASC so it doesn't complain. You don't need to include the Macromedia Flash classpaths; MTASC comes with its own.

  • The filename of our final compiled .SWF file, which I want to be separate from the "assets" file.

Here's how my project breaks down as far as directory structure; I'll be using this in the compilation example:

  • my application's classpath:
    d:devmyprojectflashclasses

  • filename of startup class:
    d:devmyprojectflashclassesappApplication.as

  • path to graphics assets (named movieclips in the library):
    d:devmyprojectflashassets.swf

  • path to other libraries, in my case animationpackage:
    d:devflashanimpackage

  • name of the final output file:
    d:devflashmymovie.swf

The next step is to create an MS-DOS batch file that will execute the mtasc command line compiler. Making this batch file will allow you to double-click the batch file to compile; you could also run it from the command line directly by typing the full name (include the .bat extension). Here's what the batch file looks like:

Line  Batch File Line
01    "D:/dev/mtasc/mtasc.exe" ^
02     -main ^
03     "d:devmyprojectflashclassesappApplication.as" ^
04     -swf "d:devmyprojectflashassets.swf" ^
05     -cp "d:devmyprojectflashclasses" ^
06     -cp "d:devflashanimpackage" ^
07     -out "d:devflashmymovie.swf" ^
08     -version 8 ^
09
10    pause 

Instead of copying/pasting this example, you should download this file by right-clicking and choosing "save link".

If it's been a while since you've seen a batch file, the ^ symbols are MS-DOS "line continuation" characters, which makes the file a lot more legible. Here's what's going on:

  • Line 01: This is the MTASC compiler program. Everything after this is a parameter that tells MTASC what to do.

  • Line 02: Tells MTASC that the "startup class" has a main() static method, and that the SWF should start program execution there.

  • Line 03: The "startup class". MTASC will automatically parse and recursively compile all other classes, starting with this class. If you tested your application in Flash before converting it, then everything should be fine.

  • Line 04: The swf file that has all those named Library assets that you're using with methods like MovieClip.attachMovie(). If you're not using any, you can just leave this out and replace it with the -header option, which will create a brand new swf file. See the MTASC documentation for more.

  • Line 05: The classpath to my project's Actionscript files.

  • Line 06: The classpath to my installation of AnimationPackage. If you have other classpaths, just add more like this.

  • Line 07: Specifies the name of the output SWF file. If you don't use this, then the file specified in Line 04 is used, leaving all library elements intact. I have them separate because I like the idea of having my asset files separate from my compiled output.

  • Line 08: Tells MTASC to compile for Flash 8 instead of the default. Note that there are some missing definitions in the Flash 8 Video object, so if you get any undefined parameter errors, you'll need to go into the MTASC installation directory, go to the std8 directory, and edit the appropriate intrinsic class file.

  • Line 09: Left blank, so the previous line's trailing ^ spills into it and doesn't collide with Line 10.

  • Line 10: Pauses the output of the command, so you can read it if there's a problem with compilation.

Once you're done editing the file for your own purposes (there are instructions in the REM statements to help you), give it a whirl by double-clicking the icon (remember it has to have the .bat extension to run, and you need to use full pathnames in the file). If you're a masochist like me, type it into the command shell.

  • If you're having a good day, you should see the command line executing, and quite probably some compilation errors; MTASC is a lot pickier about the correctness of your code syntax compared to the Macromedia Compiler, so you'll probably have some cleanup to do. There are also some things you can't do in MTASC, like nested functions, referring to static class properties inside anonymous functions without fully qualifying the package name, or leave extra ; marks lying around. I'm still figuring it all out, so don't ask me for help...I probably won't know :-)

  • If you see any errors related to missing files, you've goofed up...go back and make sure everything is correct. I will have no patience for your typos, but will accept responsibility for mine :-)

That's It!

I'm feeling a little better about using MTASC for future projects. My next step will be actually picking an IDE like Actionscript for Eclipse, or possibly trying to figure out how to make this work with Flasc or Enterprise Architect. I'm just starting to look at these.

Hope this saves someone a bit of time...enjoy!

Language Fluency

POSTED 04/09/2006 UNDER DesignProgramming

I've spent the past several days working on several programming projects, switching between Actionscript 2.0, PHP, SQL, and HTML/CSS. In hindsight, I've been deeper into the programming flow than I have in some time, to the point of being reclusive. The question on my mind: why haven't I gone nuts from switching between languages?

My working theory: like most older programmers, I have that "deep structure" in my brain that is familiar with a certain family of common computer languages. As a result, I have a rather casual attitude toward programming in general: I don't worry about it too much because I know I can figure it out. I can't claim to be a master of any particular one, but I can get around without too much trouble.

On a related note, I have several friends who can converse in multiple languages like Italian, Japanese, and Russian. Learning foreign languages was something I was never good at in school, though I'd taken years of Mandarin Chinese and French. I thought I just didn't have the knack for it, painfully aware of my awful pronunciation and grammar.

Thinking of my relative comfort with computer languages, I found myself wondering if there was some basic mechanism that applied to both programming languages and foreign languages. For example, if I can be comfortable with the broad family of C-style languages and concepts, perhaps this is analogous to someone comfortable with speaking a whole bunch of romance languages? Is there an exploitable commonality here?

FYI, I am not making the statement that a computer language is comparable to a full-blown spoken/written language, though I heard a story about a kid in my high school whose parents tried to get him out of the foreign language requirement in this way: they claimed that Pascal was a foreign language.

Anyway...

From my perspective there are three elements that must be mastered before you can consider yourself a competent programmer. These are, in no particular order:

  1. Computer Language Syntax and Grammar
  2. The Development Environment
  3. Algorithms

1. Computer Language Syntax and Grammar

This is the easiest, most mechanical part of "learning" a programming language. There are usually only a few dozen keywords to know, a handful of conditional structures, a smattering of data concepts, and that's it. You can summarize most computer languages on a single piece of paper (both sides).

I should mention that computer languages have one inherent advantage over real languages when it comes to learning them: the learning environment is the real environment (usually). You write the program, the compiler provides you rapid feedback about what you're doing wrong, and you learn what each language element is capable of doing through practice. The grammatical patterns become ingrained with actual use.

I didn't find this to be the case in high school. When I was learning French, the environment was synthetic and non-immersive. Even in English class, I had a terrible time with grammar because we learned it through pattern drills; this was utterly useless to me, because I am terrible at this kind of memorization. I did much better at intuiting my way around words; since I couldn't remember any of the rules, I had to think whether what I wrote actually made sense. That was, to use a computer programming analogy, my "compilation" test: by reading back what I had written, I could visualize a piece of paper being "smoothed out". If a phrase generated a logical confusion or ambiguity, that was an error that made the paper "rough". When the paper felt smooth enough, I was done.

So the easy part of learning a computer language is getting those few dozen words down. The hard part is learning useful compound phrases. This is more than being able to throw out timeless nuggets like "Où est la salle de bains?"; the analogy in writing prose might be learning how to express an idea in a sentence.

Most computer statements can be very brief, but are in themselves are rather uninteresting. Compare:

The dog is red.

to

color.dog = 0xFF0000;

You can't write an interesting essay out of simple statements like that; similarly, you can't make a real program out of simple declarative statements (you've made a settings file, which is still useful). To get more interesting, you've got to have a few trusty phrases in your arsenal. I just looked back at my last two posts and came up with a list that probably covers 80% of the sentences I use:

  • the setup statement, followed by hypothesis
  • the observation, followed by interpretation
  • the supporting list of facts, objects, whatever
  • the clever closing line
  • the breezy lightening remark
  • the aside into silliness
  • the sudden change of tone
  • the run-on sentence to effect boredom
  • the planting of an idea/phrase for later callback
  • the callback
  • the juxtaposition of disparate ideas

I'm not sure if this is "grammar", but it's how I think of writing. I start from the beginning, and deliver short lines of prose that hopefully convey information + insight, with a dash of personality.

In programming, there are certain constructs that express recurring ideas when strung together in just the right way:

  • the conditional loop
  • the branching control statement
  • the iteration over a set of data
  • the efficient initialization of complex variable types
  • the conditional setting of variables
  • the testing for anomalous conditions
  • the dynamic allocation of resources
  • and so on.

This is a level of complexity that's just above simple declarative statements, but just below the implementing data structures and algorithms.

Moving up from sentences, we get into collections of sentences, then entire paragraphs that have some kind of point, and then entire essays that have some larger point, followed by longer works that have many points. And there are corresponding structures and approaches that work in all those cases. Programming is not that much different, from a certain altitude.

2. The Development Environment

Until you apply that language in a real environment, it's just an intellectual exercise; computer languages aren't very interesting unless they are used to actually do something. It would be like going to all the trouble of mastering French and never going to France, or at the very minimum talking to interesting French women, oui?

The modern development environment consists of approximately one zillion code libraries, each written by a programmer who is possibly crazy. The trick is to find which packages are absolutely necessary (because there is no other choice) and which are really really good. If you had to choose the breakfast cereal to base the next two years of your breakfast lifestyle on, with no chance of going back, you start to get the idea. The use of code libraries theoretically prevent you from having to re-invent the wheel. Back in the 70s and early 80s, re-inventing the wheel was easy because machines had less memory than a small desktop icon uses, but times have changed. For one thing, the Internet has made it possible to find all the other code libraries. Yay. Secondly, the increased sophistication of graphical, networked computer operating systems puts the modern development environment at about the same level of the Tax Code. Possibly higher, because the Tax Code doesn't have showstopping bugs (we just call 'em loopholes and look the other way).

The real-world equivalent of the Development Environment is perhaps culture and society. While a lot can be traced back to basic human traits, every culture essentially has its own custom API, which is geek talk for Application Programming Interface. An API is a set of programming conventions that allows one fluent in a langauge to use a programming service. An example of such a service could be something like drawing a 3d polygon on the screen or making a connection to a database to retrieve a row of data. You use those keywords and programming fragments in the computer language to manipulate the API, therefore getting things done without having to do all the world yourself. Meanwhile, back in the real world, we have conventional procedures like "how to have a pizza delivered to your house in 30 minutes or less", accessed through a standardized interface (the telephone) through the communication of a standardized protocol ("I'll have a large pepperoni. My name is Dave. My address is Blah Blah Blah."). Of course, in some parts of the world the idea of home pizza delivery is just crazy talk, so there isn't an API that you can use. So you're forced to do without, make your own pizza. Bummer! A motivated individual would create a new business to deliver pizza, which is not unlike a programmer creating a new code library to solve a problem. But I digress.

If "computer language" maps to "development environment" does "spoken language" map to "culture" in an analogous way? In other words, does being fluent in a spoken language necessarily imply a fluency in its associated culture? I don't think this is the case...one can be fluent in C++ and understand, without a whole lot of trouble, the idea behind Java. This is kind of where I am with respect to computer language fluency. Analagously, one could be pretty fluent in Spanish and communicate with a wide range of Latino communities. I suspect you could even annoy many Puerto Ricans ("I'm not Spanish!") in the process, and still they'd get the gist of what you're trying to say.

Even with the ability to speak the language, you probably would not be able to engage with the society at more than a surface level. You are missing the history, the culture, and the sense of identity that comes from growing up with it. Looking back at programming, I could say the same thing about my knowledge of PHP. It's part of the standard C++ like family of languages, which I speak, so I am not unlike traveller hopping from environment to environment. While I can't claim deep familiarity in any of said environments (and by extension, the communities that have formed around them), I am conversant enough to at least orient myself and "find the bathroom", so to speak.

3. Algorithms

In our rush to make things happen, we usually think of algorithms last. We want to make things now, and as neophytes tend to see only the surface.

Algorithms are ways of solving certain well-defined problems, and consist of a logical set of steps built on a flash of insight. At the level closest to implementation, algorithms are like cookbook recipes: follow the steps, get a nice cake. While I like cake, I am more drawn to the flashes of insight. I ask how did that flash of insight occur? Under what conditions does it occur? And how did it alter our fundamental perspective of the problem? The story of an algorithm is the Hero's Journey, telling of difficult challenges faced in a series of real-world tests. The challenges met, the Algorithm returns home with results in hand, and the world is a better place for it.

In the real world, algorithms are the "way we do things around here", what Neal Stephenson calls "the operating system of society". In his cyberpunk novel Snow Crash, Stephenson referred to the Sumerian idea of me:

[...] the decrees of the gods [...] that make civilization, as the Sumerians conceived of it, possible.

The decrees, as described in Snow Crash, were not confined to spiritual matters. They provided instruction on how to conduct civilization itself: when to plant the crops, when to bring in the harvest, and so forth. In today's world, we don't have things quite so cut and dried, but there certainly are "standard practices" that we have grown to take for granted, civillization as we know it: The bi-weekly paycheck. The 9-5 workday. The Home Mortgage. The Baby Shower. Team Spirit. These are ideas tied to our daily social experience, designed to solve certain problems, actively shaping our use of language with new words and expressions.

Aside: I'll just mention that the idea of "languages shaped by experience" reminds me of Delphi, Python, and Ruby (computer languages all). Not that I know any of them, but in my mind that's where I file them away (under: "computer languages, worth looking into someday").

Understanding the totems behind societal (process) expectations is as much a part of the language as the world (dev environment). The world (dev environment) is comprised of the things we talk about (the hardware/software APIs programmers use). Societal conventions (algorithms) are what we do with them, in pursuit of fulfulling some role (making software that works).

Knowing the history of a place helps put things into perspective too. Take the study of modern idioms, for example, or "getting" jokes based on current events. In computer environments, we have expressions like "strings", "ls", and "reboot"; these have ancient roots that are a part of my foundation, and therefore color my understanding of computer systems. When I look at a computer, I see basically an overgrown version of my 8-bit micro. Sure, there's more STUFF in it, but it's still all memory-mapped I/O driven by a CPU that accesses banks of memory, its cycles scheduled by some kind of hardware interrupt mechanism to share the system bus with other coprocessors. And therefore, it does not scare me. Maybe it should, but it doesn't.

Concluding Thoughts

I have no strong conclusions to share, but in summary this is what I was trying to say:

  • I seem to be fluent in computer languages, and am able to move from language to language without too much stress. Why am I not going insane?

  • I have never been able to pick up a real language like French or Chinese, for whatever reason.

  • Knowing a computer language by itself isn't enough to be a programmer; there are at least two other areas that require study and experience. The sum of all three is what has lead to my "fluency" with programming in general ("best practices" born of experience might be the fourth).

  • Similarly, learning a language--say, Spanish--has the implication that there's more to it than just the grammar and vocabulary. The environment, the culture, and the operating procedures are all part of the package.

  • The primary difference between learning a computer language and learning a foreign language is that I've had confidence in knowing what I'm dealing with. It's easy to be overwhelmed by number of details, unless I know one thing: it's just a computer. And I know exactly what a computer is. It is the same problem at a different scale compared to my old 8-bit Apple II, but the method of attack is pretty much the same.

  • So what is it that would give me the confidence in learning a real language, that I missed when I was a kid? Is there an insight that would make this into another kind of problem I know how to handle? Breaking it down into syntax, culture, and operating procedure and then re-integrating it into an immersive learning environment might be one way. Maybe just diving in and babbling, suspending all my foolish notions of being "being adult" so I learn how to make the sounds correctly.

Food for thought! Time to get back to work, though, to start plowing another field of code.

Getting OOP to Speed with AS2

POSTED 11/23/2005 UNDER FlashProgramming

"How to explain things to those new to Flash who are still putting code on buttons" is one of the framing statements in Ben Jackson's article on Teaching OOP that really nails where new coders are coming from. Putting actions on buttons is kind of like learning how to draw a frog: a new ActionScripter learns how to make things happen right away, but creating a larger program requires the ability to compose and coordinate many things together, as allowed by the available programming tools...

There are two main tools that Flash ActionScript 2 gives you as a programmer: the language, and the Flash environment itself.

  • The ActionScript 2.0 Language: ActionScript 2.0 without all the trimmings is pretty lean. If you know what the statements and operators do, that's all I'm talking about. This is the bare, naked language that you'd learn in an introductory programming class. Do you know what all the statements and operators do? You really should.

    There's not a lot to know, since the statements don't do very much by themselves. That's why intro programming courses can be so boring...they focus on the language itself, which is basically grammar. If you like grammar for its own sake, fantastic! If you'd rather see something move, you're actually interested in the Script Environment.

  • The Flash Scripting Environment: This is what makes ActionScript 2.0 interesting...what you can do with Flash is all about what is provided to you already. With the language you issue commands, but without the Environment you have nothing to boss around.

    The Environment consists of all the special graphical objects like MovieClips and TextFields, built-in classes that provide useful functionality (like talking to a web server) or packages data (like Arrays and Strings). The environment also includes all the built-in functions that do Flash-specific things. The Script Environment is what "makes Flash Flash". You could theoretically take the ActionScript Language and apply it to, say, a garage door opener, but the environment would be different because a garage door does different things: you'd have built-in objects like Motor and Sensor instead of MovieClip and Mouse.

You can think of the Environment as a bunch of pre-packaged objects that either do things on the screen, control the computer, or extend the language. The Language is what allows you to express yourself with those objects. Some objects are always around (System objects), some have to be created. Sometimes there's just one of one kind (like the Stage), and at other times you'll want to create multiple objects of the same type. That's all we mean when we say AS2.0 is "object-oriented".

There is a lot of stuff in the Environment. Usually learning the language isn't too bad, because programming languages tend to be largely the same in the set of features: they just are in different places. It's sort of like when you climb into an unfamiliar car and are try to figure out how to turn on the headlights...the basic concepts are pretty much the same from car to car. Learning a new Environment, on the other hand, is like starting a new job at a new workplace. Eventually, you learn what does what in the company, learn the new jargon, and adapt to the way things are done. The best reference books I'm aware of are the ones from Colin Moock; however, I'm not sure how accessible they are to the beginning Actionscript Programmer who just wants to know what's what.

Objects versus Object Oriented Programming

Because of the amount of literature written on Object Oriented Programming, it sounds like a really complex subject. From the language and environment perspective, though, it's not complex. All it means is that you can group functions and data into one lump, almost like a little mini-program, and we're going to call this lump an object. That's it. Many of the really cool features of the Flash Script Environment are packaged in these object thingies, so to use them we need to use the other bits of AS2.0 that allow us to access the data and functions inside them. Hey...that's being object-oriented!

Don't get me wrong...there is a lot to Object-Oriented Programming (OOP), but even that is something of an overblown concept. OOP is a set of best ideas regarding the use of objects to make life better for the programmer. In software engineering, we generally want features like scalability ("what if I wanted to make this really big?"), maintainability ("can my coworker work with my code if I'm on vacation?"), robustness ("does it always work?"), expandability ("I want to add a couple new things and not do a whole lot of extra work"), and so on. These features are not specific to OOP, but OOP was designed to help implement them in an easier way. An OOP-capable language just provides the special statements to make it easier to express those ideas in an object-oriented fashion; in other words, you can't easily create an object if there is no command to do it.

There is nothing stopping you from using Objects independent of OOP practice. And you shouldn't feel ashamed of that, if it gets the job done. If you're just getting used to the idea of using Classes, think of them as just a group of related functions that have their own shared data, and try to structure your code that way. The "mini program" analogy isn't a bad one. I think you'll find, as you play around with the idea of grouping related functions together, that object-oriented questions start to come up naturally. Then, all that fancy OOP reading on inheritance, subclassing, composition, and polymorphism may start to make sense. In the meantime, just screw it...they are just labels for simple concepts that we'll talk about later.

But Wait, OOP isn't the Problem

I feel bad for saying this just as you were starting to feel better about OOP, but this is not the real challenge in learning ActionScript 2.0 in Flash. If you've had more than one button on the screen, you've experience the chore of keeping track of what code fragment is doing what when something gets clicked. This is event driven programming, and OOP doesn't make these challenges don't go away. You need to have a grasp of how events drive the flow of control before you can really do anything cool in Flash.

Challenge: Adapting Old Techniques from the Internet
Compounding the problem is that the majority of code fragments on the Internet use event methods that date back to Flash 4 or 5. As soon as you try to use them in an OOP-y way, everything breaks. That's because the event handlers you are used to writing look like this:

    // mc is a movieclip instance on the Stage 
    mc.onPress= function () {
        trace("boo! we are pressed!");
    }

You might be tempted to try something like this with objects:

    // DoSomething is a class we make with a function called pressed() in it
    var pressHandler = new DoSomething();

    // mc is a movieclip instance on the Stage 
    mc.onPress = pressHandler.pressed;  

That won't entirely work, because the onX handlers for MovieClips are implemented as a function callback, which doesn't entirely work with functions inside an object. BTW, "functions inside an object" are called methods. The loaded() function will get called, sure, but none of the other variables (called properties) in your objects will be accessible! There's a technical reason for that, but I won't go into it now.

The takeaway is this: movieclip callbacks do not work with objects. You need to find another way of detecting events; in Flash MX 2004, that's by using listeners instead of callbacks; for MovieClips, you'll want to look at the Mouse and Keyboard objects to achieve the same functionality with "Listeners". Yet another way is to manually reconnect the object context.

Challenge: The Compiler Doesn't Help You Unless You Help It
How many times have you discovered your code isn't working because you had the wrong NAME of an object or property, and Flash didn't tell you? That's what I'm talking about...this reminds me of the head-in-the-sand mentality of not telling someone that the house is burning down because it might be "upsetting". Fortunately, in AS2 starting with Flash MX 2004 we could add type-checking, which allowed the compiler to catch such problems.

The good news is that it works really well. The bad news is if you're too lazy to add datatypes to your variable declarations (and objects are a kind of variable), it doesn't work. The properly typed example would have been like this:

    // LoadDisplay is a class we make with a function called loaded() in it
    var pressHandler :DoSomething = new DoSomething();

The example still won't work, but if I had done this by accident:

    // pressMe() doesn't exist in the DoSomething class
    mc.onPress = pressHandler.pressMe;  

...the compiler would have caught that loadedMovie wasn't actually a method defined in the LoadDisplay class. And I would have one less problem to debug.

That's All For Now

So that's on my mind right now. What I'm trying to say overall is this:

  • Conceptually, objects are just a way of packaging functions and data together.

  • Object-Oriented Programming (OOP) is a methodology for creating programs with desirable qualities like maintainability, robustness, and so forth. AS2.0 has new statements in it---most notably, class and new--- that allow the programmer to create objects.

  • There's a lot to OOP, but it's actually pretty common sense stuff. All those mysterious keywords associated with the class statement---private, static, implements, and so on---are directly related to creating objects that support the best practices in OOPing. But you really don't need to use them until you're ready.

  • The other main challenge in using AS2 in Flash is event-driven programming, because the tried-and-true methods you've used in the past don't quite work with Objects. The reasons are a bit esoteric, and are related to Flash's sordid past. However, there are ways of working around it.

I haven't yet touched on how to make the connection between the big ideas in your head and these topics. For that, you need to have a different methodology: Learning how to structure your ideas into shapes that can be expressed through the script language and script environment. That's when things really start to get interesting...

Explaining Actionscript 2.0 Classes without OOP

POSTED 11/22/2005 UNDER FlashProgramming

A friend of mine, just getting into more advanced programming topics in Macromedia Flash, asked me what classes were.

"That's an excellent question!" I beamed, pleased at the opportunity to share some hard-won knowledge. "They're useful for constructing object hierarchies--"

"What are objects? And why are there hierarchies of them?"

"Well, you can model a problem as a series of interconnected objects..."

"Huh? Why? Where do you put them? Are they files?"

Uh oh.

There has to be a better way of explaining classes to people without going down the tired old "Classes allow you to build object-oriented programs that make it easier to model real-world problems" explanation. The entry in Wikipedia is a great example of a definition that makes absolutely no sense to a beginning programmer:

In, object-oriented programming, a class consists of a collection of types of encapsulated instance variables and types of methods, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that consists of a particular kind of compile-time metadata.

It just gets worse the more you read. It's all technically correct, but like a lot of technical writing it tends to describe rather than explain. Which is pretty useless when you're trying to understand something new.

So I'm thinking next time some asks me about classes in Flash, I'm going to try explaining it first in non-OOP terms.

  • Classes allow you to group functions and variables together. You do this by using the class statement, which contains all the functions and variables that you want to be related to each other. This can make it a lot easier to organize your program into groups of classes, as opposed to huge lists of functions.

  • Once you define a class, you can treat it as a new kind of data type. You can create new instance variables of a class you've defined using the new statement. To use the functions and data that you have defined inside the class, you use dot notation on the instance variable.

  • Class definitions can also be used to organize your global variables, if you use the static keyword. This is far more useful than using the _global object.

  • A lot of Flash's built-in features are packaged in the form of pre-defined classes, so learning how to use classes is essential to unlocking the advanced features of Flash's script environment.

  • There are two other big advantages to using classes in AS 2.0: the compiler will be able to find errors and tell you what is wrong, and you can put all your source code inside the Flash Project Window. No more hunting for script fragments inside of your buttons and movieclips...they're all in one place, finally.

At this point, one has to start talking about how to set up classes syntax-wise, explaining classpaths and packages, and the "one class per file" rule. I think one could probably defer a discussion of object-oriented programming until after the syntax is understood.

However, I think a lot of Flash programmers come at AS2.0 from a "I want to do X" perspective, and they they just want to know what properties to twiddle so the right thing happens. Do you force them to understand classes and object hierarchies?

Sleepy, will reflect on this later.

UPDATE: I'm starting to dump some thoughts into the blog as a kind of "think aloud" exercise. The next part is here.

A Quick Tour of Visual Studio

POSTED 10/16/2005 UNDER GweepingProgramming

466-1015-vcs-title.jpg

I catching up with Peter, who among other things teaches an Introduction to Visual Basic at Endicott College. I commented, as I do every time we meet, that I should really look into VB because there's actually quite a lot of work being done in this environment. There are a lot of "real applications" are being done in VB. I'm not sure if there are more than for Flash; a quick visit to Monster.Com showed a 3:1 demand for VB coders versus Flashers, at least here in my neck of the woods.

Warming further to the subject, Peter showed me how to create a skeleton application in Visual Basic .NET. The entire intro took about 10 minutes, more or less. The amazing thing is that this is all I needed to get enough of a grasp of the environment to know what to do next. I imagine that any experienced Actionscript coder could pick it up and start screwing around.

Warning! Geeky notes follow!

Getting Started

Assuming you've got Visual Basic .NET 2003, create a new Visual Basic .NET Project. Then follow along with this diagram: it points out the bits of the Visual Basic IDE that are helpful in just getting something to happen on the screen. Go ahead...click to make it bigger!

What is What


Step 1: After you name and create the project, you'll be presented with a default Form (here named "Form1") which is the main application window. In ActionScript terms, you can think of it as the "_root movieclip". I suppose you can eventually create and manipulate other form windows, as you can with commands like MovieClip.createEmptyMovieClip() in Actionscript. I haven't gotten that far :-)

Step 2: You can select a number of components from the left panel. Some of them are visual objects like buttons and textboxes. Others are non-placed objects, like the FileOpenDialog or Timer objects. Once you select a component, you can draw them on the Form you started with in Step 1.

Visual Basic Editing Step 3: To actually write code, you double-click the component, which will open up the code snippet for you to edit. Peter just attached some code to the Button (here, Button1) that sets the Text property of the object Label1 to something else. Conceptually, it's just like what you're used to in ActionScript: you're basically writing an OnPress handler to set the Text property of a TextBox instance.

Running! Step 4. To run your program, go to the DEBUG menu and choose either START (F5) or START with DEBUGGING (CTRL-F5). Voila! You're rockin'!


Inspecting Properties

Here's some other useful things to know:

  • Selecting a component with a single click will show you its properties in the Property Window, assuming you have it showing. One of the buttons in the upper right of the screen (marked as "important windows" in the diagram) will bring up the property window. On the diagram, the green info boxes call these features out.

  • Double-clicking a component will show you the default event handler for that object. This is where you write your code. For example, double-clicking a Button will show you its "click handler". There are more handlers, of course, which you can discover by using the various tool-tip and auto-completion tools.

  • You can further explore the various object properties and methods avaiable by using the Class Browser and Object Browser windows. On the diagram, the pink info boxes point out the areas you can click.

Off and Running!

Congratulations, you've made a real Windows app! Except it doesn't really do anything, but the Visual Studio Integrated Development Environment (IDE) is very large and very interesting to explore. Now that you know how to create and run a simple program, you have a foundation for exploring the rest of the IDE. The copious tool tips, context-sensitive help, and thousands of articles on the Microsoft Development Network now have some relevance to your existence! This is what a real IDE looks like, BTW. You'll see that the editor supports code folding, which is wonderful. And the debugger is actually useful.

Bummers

One drag is that your Visual Basic .NET app needs the (surprise!) .NET runtime, which kind of sucks because it's feckin' gigantic...22MB! Sigh. And I really have no idea what it is exactly, but it makes the smooth deployment of your application a pain in the butt. Flash provides a much cleaner deployment experience, plugin-detection code aside. Unless you're deploying on CD-ROM as a stand-alone projector--ugh.

The introduction of .NET has lead to a balkanization of the Windows Programming APIs, which makes things confusing and has kept me from seriously pursuing PC development; there's just way too much stuff you have to know to get anything to happen.

Recently, however, I've come to believe that just making stuff is probably more important than total comprehension or programming elegance. In other words, I should just make something and worry about elegance later. Visual Basic .NET, though it feels a bit wizardy and bloated, will at least get me familiar with the Windows API in small, digestable chunks. I am fighting the desire to first put together a comprehensive API overview to get that "big picture" view so lacking in most code documentation; I wonder who the equivalent of Moock is on the Windows Dev side of things. THAT would be helpful.

But it's still BASIC...

I know, I know...BASIC? WHY BOTHER? It's been years since I've had to program in BASIC, and I don't really have a desire to start learning now; I've pretty much imprinted on C++ / JavaScript. The closest thing that I've had to use in recent memory was Lingo, which borrows its verbose and sometimes-ambiguous syntax from HyperTalk. Ugh. Don't get me started.

BASIC itself is still kickin' around in other interesting incarnations:

Visit Real Basic Site One noteable product is REALBasic, which was popular in some education research circles as a rapid development tool, and is now taking on Visual Basic as the crossplatform choice for rapid application development. I last looked at it three or four years ago, and the Windows side did not seem as stable as I would have liked. I hear it's greatly improved these days, and they've added Linux to the list of supported platforms. It's priced comparably to Visual Basic for Windows: $99 for the Standard edition (free on Linux), $399 for the Pro version.

Star Wraith Then there's Dark Basic, which is a game development BASIC for Windows. You can create 3D game worlds with this package, all for a mere $49. If you want to get into a language that allows you to actually make stuff right away. And therein lies the power of BASIC: you can do stuff right away, without all the tedious mucking about with compilers, linkers and what have you. I should dig up my license and upgrade to the latest version.

Those look cool, but...

Yeah, I wasn't entirely convinced either, so I tried out Visual C# (pronounced "C-sharp") and Visual C++ to see how they handled the .NET side of things; Visual C# in particularly has both Java-like syntax and the Visual Basic style interface.

Check out and compare these screenshots; just look at the window title to remind you which language you're looking at:

Visual C#: Form and Edit Views ("Windows Application Project")
Form Form


Visual C++: Form and Edit Views (".NET Windows Form Application")
Form Form


And for comparison again with Visual Basic...
Visual Basic: Form and Edit Views ("Windows Application Project")
Form Form


They're all very similar, so if you want to get the flexibility of Visual Basic I suppose you can just start with C#. I think C# is a .NET-only framework, but I'm not entirely sure. Visual Basic may also have a lot more code modules available for it in the form of COM components (the precursor to .NET). I'm trying to get some people together locally to attack the learning challenge as a group. Like I need another project, but development of real software is one of my long term goals. I dunno why...I just like the feel of a solid desktop application. It probably has something to do with my increasing age and fading attention span...why, back in my day, we had to hand-assemble our opcodes on 8-bit processors, with only 3 registers and...Zzzzz.

Page 1 of 5 pages  1 2 3 >  Last »
Thank you for printing this article! Please note that all material on this website is copyrighted by either David Seah or individual comment contributors. To request permission for republication and distribution, please contact David Seah (http://davidseah.com/contact).