Jesse was born and raised in Australia, and now lives in London. He is one of the original founders of http://ActionScript.org, and was formerly a Flash developer, teacher, author and speaker. While Jesse no longer works as a full-time Flash professional, he still enjoys actively participating in the http://ActionScript.org community as time permits.With the introduction of Flash MX and the push towards Flash as an application development medium, loading content on the fly is becoming ever more important. In the near future I'll be putting together a comprehensive intro to XML and Flash for the uninitiated, but for the time being I'll write up this quick tutorial on loadVariables as it's still invaluable, even (perhaps especially) in Flash MX.
This tutorial will assume you're using Flash 5 or above, and the later sections will cover Flash MX specific topics.
LoadVariables was introduced in Flash 4 but as with many other Flash 4 functionalities, only realized its full potential in Flash 5. In Flash MX things have been made even sweeter but let's not get ahead of ourselves.
LoadVariables allows you to load in data from an external source provided it is formatted appropriately. Most often this external source is a static text file, but that needn't be the case. Dynamically loading text content is great for making easily updatable, extensible web applications and sites. For instance, say you are developing a web site for a client with little or no technical knowledge, who does not own a copy of Flash but wants to be able to update their own website as easily as they might using MS Word or some other (yuppie) application. If you hard-code your text content, such as ‘Site News' or the like into the application, you've just lost yourself a client.
As mentioned above, Flash will spit the dummy if your target file isn't formatted correctly, so before we get into coding, let's explore the proper format for a file which we intend to load later on. The first thing to note is that the ampersand character (‘&') is used to denote the beginning of a new variable. A single equality symbol is used to separate the variable name from its value. So the following is valid:
&siteNews=Something amazing happened on the way to the nerd convention!
Note that spaces after the equals sign are perfectly legitimate, but try and stick them between the ampersand and the variable name, or after the variable name, before the equals sign, and you'll just cause yourself trouble. Be vigilant!
Most of the time we want to load more than one variable from a file. Remembering that the ampersand always precedes a variable name, that's done in the following manner:
&siteNews=Something amazing happened on the way to the nerd convention!&linkToStory=http://www.actionscript.org/
Note that I did not include a newline, or any white space characters at the end of the first variable's value, I just added an ampersand and began the next variable. Why? Because if you include a newline, or a few blank lines so your text file looks pretty in a text editor, they are, as far as Flash knows, part of your variable as well, so your variable will be a sentence including a whole stack of newline characters at the end. We'll deal with how to eliminate catches like this towards the end of the tutorial, in the section on Parsing.
Just to clarify, even though the above script is one long String, Flash is clever enough to see the ampersand and realize it's two variables, so once the loadVariables operation has completed, we'll be left with two variables named siteNews and linkToStory, with their respective values filled in.
The next most important thing to note about loadVariables in Flash is that everything is loaded in as a String. If you don't know what a String is, try reading the Variables tutorial. For instance, the following is perfectly legitimate, but may not have the desired effect.
&hoursInJessesDay=29
So you load this into Flash and tried the following:
[as]myVar = hoursInJessesDay + 5;Any bets as to what that will output? No, not 34. It will output 295. Why? Because you loaded 29 in as a String, and the + operator for Strings just whacks the second argument after the first (concatenates). Don't despair though, there is hope. You can use the parseInt() or Number() methods to convert the String to a fully mathematically sound number for use in all your math operations, once it's loaded. We'll get to that in the swonking section.
So now you know the rules. Let's take a look at the code.
Many of you will have used loadMovie and will know that it comes in two flavors: loadMovie and loadMovieNum. Well, loadVariables is exactly the same. You can load in content using loadVariables or loadVariablesNum. loadVariablesNum accepts two arguments (generally); a file to load the values from, and a Level to load them into. As levels are annoying and bothersome I'm going to skip over this as much as possible. Suffice to say the following code will load a set of variables from file.txt into Level1:
[as]loadVariablesNum("file.txt",1);[/as]Keep in mind variables loaded into a specific level will need to be referenced (from outside that level) using _levelX.variableName, where X is the level number. From within that level they can be referenced using _root. That's all covered in my Paths tutorial.
With that out of the way, let's get to my preferred instantiation: loadVariables. loadVariables also accepts two arguments; the first is again the name of the file to load but this time the second is the instance name of the movieclip which will accept the variables. Users of Flash MX should note that you can use loadVariables with the arguments you would normally use for loadVariablesNum and it will pick the correct operation for you. So, in it's most basic form, the loadVariables code to load variables in a file, file.txt into the timeline of an MC in the current movie with instance name ‘holder' would be:
[as]loadVariables ("file.txt","holder");[/as]Note that the second argument above is a String, surrounded by quotes. While it will often work if you make it a reference, that's not the best idea for various reasons. Also, just to bat you all over the head with the Object Orientation bat; it's probably wiser to write the above code in the following form:
[as]holder.loadVariables("file.txt");[/as]This code does exactly the same thing as the code preceding it, but it's nice to read and more widely used. And better… I think.
Continued overleaf...The simplest and probably most common use for loadVariables is to update text fields on the stage. As in the earlier example, if you create a site with one area of text which requires regular updates or changes, loadVariables is ideal. Simply create a dynamic text field on the stage where you want your values to be displayed and set its variable name to ‘news' or something appropriate. Next create your text file (‘sitenews.txt' for example) and throw in an update:
&news=Today nothing much happened.
Save your text file and add the following action to your movie:
[as]_root.loadVariables("sitenews.txt");[/as]This should make your text appear within the text field in your SWF. Hey presto! The above code treats _root as the target movieclip for our variables (this is perfectly legal). Also note that if your text doesn't look as pretty as it might had you typed it manually within Flash that's because your font isn't embedded; embedding the font in the field should solve the problem.
The next most common use for loadVariables is probably to update data in a system which changes often, such as the price of a product in an online store. This is a good example because it leads into ‘swonking' and parsing.
Swonking
Flash MX users might decide to skip over this paragraph if they intend to use LoadVars, but it's probably worthwhile everyone knowing.
Definition: Swonk, v. – to check repeatedly if a loadVariables operation is completed yet.
To the best of my knowledge it was our very own 20 Ton Squirrel who coined the term swonking. One of the most common questions about loadVariables on the forums is of the form "I'm loading variables using loadVariables, then performing some operation on them. All my code is correct but the values of my operations are always wrong". The reason for this is that loadVariables isn't an instantaneous thing. When you ask for Flash to load the file, it takes a while, depending on the size of the file and the user's connection. Thus the values aren't immediately accessible. If I have a file called "data.txt" containing a variable ‘users' with the value 24 and I execute the following code:
_root.loadVariables("data.txt");
trace(users);
The trace operation will show "0", not "24". The moral of the story is that you need to check to see if your variables are loaded before trying to use them. The process of doing this is commonly called ‘swonking' on this and other sites and generally involves the following steps.
First you add an additional variable to the absolute end of your file called EOF and give it the value ‘true' or something similar. So the contents of my data.txt from above would now be:
&users=24&EOF=true
Next you use two looping frames, a looping movieclip or a clipevent to check over and over to see if EOF is true yet. Once EOF is true, your other variables must all be loaded. It's that simple. Describing how to set it up might be a bit long winded, so just grab this source file and take a look.
Assuming we now know how to load our data in, and check it's fully loaded, we now need to give some thought to parsing.
Parsing
Parsing is a fancy word for "doing stuff to data". If you recall, above I began outlining how loadVariables could be used to update prices for products in an online store. The more studious of you will remember also however that I stated at the outset that all values loaded using loadVariables are Strings and Strings can cause problems when you try to use mathematical operations on them. The solution can be found in parsing your data appropriately.
Once you've loaded your data and swonked it to be sure it's all ready to be used, you can perform operations on the variables to convert them (if needed) into other formats. For instance if my text file contains a definition:
&userCount=24
I would use the following code in Flash to convert that from a String to a proper Integer which I can add, divide, etc.:
[as]userCount = Number(userCount);[/as]Simple huh?
Another parsing example I mentioned above related to the issue of newlines. Recall that if you have carriage returns and newlines in your text file, they will be loaded into Flash as part of the variable they follow. While this isn't really desired, we also don't want our text file to be completely illegible, so you can create a function which goes through looking for newline characters at the end of a loaded String and strips them off.
Load Means Send
loadVariables is nifty for bringing in external data to Flash, but it is also commonly used to export variables for use elsewhere. When passed an additional argument describing which HTTP method to use to send variables, all variables on the current timeline will be sent by Flash to whatever file you specify in the file argument. By the ‘current timeline' I mean the timeline from which the code is executed.
This makes loadVariables perfect for developing interaction with databases as you can send variables to a backend script (PHP, ASP, etc.) which draws upon the variables passed to retrieve information from the database, or perhaps processes the variables passed, then passes them back. See my loadVariables Interaction tutorial for more on this topic.
Macromedia, being the darlings they are, provided us with a nifty extension of loadVariables in Flash MX in the form of the new LoadVars Object. A LoadVars Object is basically just a class which implements the loadVariables operations and a few other things automatically, with built in methods to detect when the text is loaded and built in event handler allowance for the new Flash event model (see FlashGuru's tutorial).
If that paragraph scared you, come back. I'm just being a geek; you'll see what I mean in a moment. A new LoadVars object is created using the ‘new' operator, just like all other Objects in Flash:
[as]myLoadbleData = new LoadVars();[/as]
Data is then loaded in using the load() method.
[as]myLoadbleData.load("file.txt");[/as]
Once you've created a new LoadVars object you can get into using the object's built in methods. For instance, you can use the following code to determine the percentage of the text which has loaded so far:
[as]percentLoaded = myLoadbleData.getBytesLoaded() / myLoadbleData.getBytesTotal();[/as]
As you can see, these methods save us having to ‘swonk' our data. Further you can create a function which will automatically be called when the variables are all loaded, which is better still. That's done in the following manner:
[as]myLoadbleData.onLoad = function (success) {
if (success) {
// Call your parser here perhaps
} else {
// The data didn?t load at all. Display error
}
}[/as]
Note that the above code includes an argument called ‘success'. This is passed in by Flash when the onLoad function is called and is either true or false. True indicates that the load operation was successful. Load actions most commonly fail when the filename you specified is wrong.
A few important things to consider about LoadVars Objects include:
Considerations:
A client recently came to me wondering why their content didn't work in the same manner when they loaded it from the web as it did when they loaded it from their local disk. Specifically, the issue was that they had intentionally included newlines in the text file they were loading because they observed it made a nice new paragraph in their text box in Flash. Until they uploaded it. The reason for this is that different operating systems use different notations for the various types of white space. A newline on UNIX/Linux box (which most web servers are) is represented differently to the same character on a Windows machine. The moral of the story is don't rely on carriage returns and paragraph breaks within your text file. If you need to implement such things in the text file, use a special character like "|" wherever you want a newline to occur in your text file, then when you load your content into Flash and parse it, replace all occurrences of "|" with "\n" (the newline character), or similar.
Phew. 2500 words! It's amazing how you can procrastinate when you should be doing Java projects for University. As always, comments, corrections and constructive criticism are welcome. Cheers
| Jesse Stratford [email:jessestratford@actionscript.org] is the Co-Master of ActionScript.org and a freelance Flash developer and teacher. He is based in Australia and enjoys all things Flash. NB: If you have comments or feedback please feel free to email me, but please do not email me Flash questions; the forums are provided for that purpose and you will get a faster answer by posting you question there. |
If you have found this tutorial helpful, I hope that you will take 30 seconds to visit The Hunger Site where, with just one click you can make a free donation of food to a starving person in a third-world country. We do not benefit financially from this action; it is purely an act of charity. |
| This tutorial is protected by International Intellectual Property Rights laws and may not be reproduced or redistributed in full or part, without the prior written consent of the author. Unauthorized reproduction of this tutorial or its contents may result in prosecution. I've worked hard on this tutorial, please don't steal it. |