Dlean Jeans
Dlean Jeans

Reputation: 996

In AS3, load a text file into a string

I've been trying to load a text file into a string variable. The text file named text.txt containing successful. Here's the code:

public class Main extends Sprite
{
    private var text:String = "text";
    private var textLoader:URLLoader = new URLLoader();

    public function Main() {
        textLoader.addEventListener(Event.COMPLETE, onLoaded);
        function onLoaded(e:Event):void {
            trace("Before 1: " + text); //output: text
            trace("Before 2: " + e.target.data); //output: successful
            text = e.target.data;
            trace("After 1: " + text); //output: successful - yay!!! it worked

        }

        textLoader.load(new URLRequest("text.txt"));

        trace("After 2: " + text); //output: text - what??? nothing happened??? but it just worked

    }

}

Output:

After 2: text Before 1: text Before 2: successful After 1: successful

Upvotes: 3

Views: 897

Answers (1)

axelduch
axelduch

Reputation: 10849

You are facing a synchronous vs asynchronous problem

The function onLoaded is called asynchronously by textLoader when Event.COMPLETE is dispatched, as opposed to "After 2" which is called directly after textLoader.load.

What you must keep in mind is textLoader.load is non-blocking which means "After 2" is probably (you can assume always) executed before onLoaded.

If at this point of the answer you're still confused, I'd say that loading a file takes time and executing an instruction may vary in time but is mostly infinitely shorter than it takes to load a file (imagine this file is 4go large). You cannot predict what will happen, maybe the disk is already very busy you may need to wait! But you could use this precious time to do something else totally independant from the text file, and that is why it is sometimes made asynchronously by programming languages (php for example loads a file synchronously).

Next step


Now that I have explained that "After 2" does not really exist, you have to use "After 1" as an entry point but nothing helps you from making a function named afterLoad which you would call like this

public function Main() {
        textLoader.addEventListener(Event.COMPLETE, onLoaded);

        function onLoaded(e:Event):void {
            trace("Before 1: " + text); //output: text
            trace("Before 2: " + e.target.data); //output: successful
            text = e.target.data;
            afterLoad();
        }

        textLoader.load(new URLRequest("text.txt"));
    }


}

private function afterLoad():void {
    trace("After: " + text); // it should work now :)
}

Upvotes: 2

Related Questions