In AS3 load a text file to line
I am trying to load a text file into a string variable. A 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
source to share
You are facing synchronous and asynchronous problem
The function onLoaded
is called asynchronously textLoader
when dispatched, Event.COMPLETE
as opposed to "After 2"
being called immediately after textLoader.load
.
What you have to keep in mind is that it textLoader.load
is non-blocking, which means it is "After 2"
possible (you can assume always) done before onLoaded
.
If you are still confused at this point in the answer, I would say that downloading the file takes time and the execution of the instruction can vary over time, but is generally infinitely shorter than it takes to download the file (imagine this file is 4go large). You cannot predict what will happen, the disk may already be very busy, you may have to wait! But you can use this precious time to do something else completely independent of the text file, and therefore it is sometimes done asynchronously using programming languages ( php
for example, loading the file synchronously).
Next step
Now that I've explained that "After 2"
doesn't really exist, you should use "After 1"
as an entry point, but nothing helps you to make a function with a name afterLoad
that 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 :)
}
source to share