RSS link icon

.

Load external data to an array


In this Flash actionscript 3.0 tutorial you will see how to load in external data from a text file, split it up and put it into an array, so we can extract separate and process separate words.

First we need to set up a few things.

We will need to make a text file with the information to load into flash, so open notepad or your favorite plain text editor, type in the following line, we separate every word with a comma, which will be our separator.

flower,plant,apple,orange,kiwi,banana

Now open a new flash document and type in the following code into the actionscript panel.

I have written some description text with the code lines for you to better understand whats going on.

//First we create a loader to load the information from the text file
var myLoader:URLLoader = new URLLoader();

//Here we tell our new loader which file to handle (words.txt).
myLoader.load(new URLRequest("words.txt"));

//Adding an eventlistener to listen and execute a function when
//myLoader has loaded the text file.
myLoader.addEventListener(Event.COMPLETE, textLoaded);

//Now we create an array to hold the content of the text file separately
var allWords:Array = new Array();

//Now here is the function that is executed when the text file has been loaded
function textLoaded(event:Event):void
{
    //this function takes the words string "a.jpg,b.jpg,c.jpg" 
    //and splites it into 3 separate strings in the array.
    var wordString:String = event.target.data;
    allWords = wordString.split(",");
    
    //Just for fun we test some of the words in the arrry.
    //first all words in a string
    trace(allWords);
    
    //then just word one and two
    trace(allWords[0] + " " + allWords[1]);
}

I hope you liked this small tutorial on how to load external data into an array and how to extract separate words.