Reputation: 148
There's my problem: I want to load the data from a text file (Named "myText.txt") with Flash CS5.5 . It contains some lines, and I want to store these lines in an Array. This is what I've got from now:
var myLoader:URLLoader = new URLLoader(new URLRequest("myText.txt");
var myArray:Array = new Array();
myLoader.addEventListener(Event.COMPLETE, loadComplete(myArray));
function loadComplete(myArray:Array):Function {
return function(e:Event):void {
myArray = myLoader.data.split("\n");
for(var i:int = 0; i < myArray.length; ++i){
trace(myArray[i]); // To check if it works at this point
}
}
}
for(var i:int = 0; i < myArray.length; ++i){
trace(myArray[i]); // To check if it gets modified
}
The fact is that the fist part works, it loads the text file and it stores in myArray
, and traces it; but it stores only in the local version of myArray
, it doesn't modify the reference, so the for
outside of the function doesn't trace anything.
I had read that Arrays were passed by reference in flash, so I don't understand why it doesn't work.
I would appreciate the help.
The thing now is that this is just a test file, I want this code to be in a function that I will use a lot. The ideal would be to have a static function in an AS Class File named "Utils", with other useful functions. The code of the "Utils.as" file would be like this:
package Include {
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
public class Utils {
public function Utils() {
}
public static function fileToArray(path:String):Array {
var linesArray = new Array();
// Code to load the file stored in 'path' (the 'path' String
// also has the name of the file in it), split by '\n' and store every line
// in the 'linesArray' Array.
// Example: path = "file:////Users/PauTorrents/Desktop/program/text.txt"
return linesArray;
}
// other functions
}
}
Thanks for the help.
Upvotes: 0
Views: 1402
Reputation: 14406
A few things need addressing here.
First, your for loop at the end will always run before the load completes, so it will never trace anything. AS3 does not lock the thread when a URLoader loads, so it will move on with the rest of the code in the block while it waits to load the file.
Second, it's really ugly returning an annonumous function as the result of your load complete handler.
Here is how I would do this:
var myLoader:URLLoader = new URLLoader(new URLRequest("myText.txt");
var myArray:Array = new Array();
myLoader.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);
function loadComplete(e:Event):void{
myArray = myLoader.data.split("\n");
for(var i:int = 0; i < myArray.length; ++i){
trace(myArray[i]); // To check if it works at this point
}
//now move on with the rest of your program/code
}
Upvotes: 1