What I am trying to do is use a function for reading a textfile, storing the variables into an array, and then return the array. My problem is that I do not know how to wait for the arrays to be populated before returning them. (see code below)
This is my first attempt at working with Flash/Actionscript 3.0. I understand the async part but I am not sure if/how I can workaround it. Nothing that I have googled has provided me with any help. I need some clarity and am hoping someone here can help provide it! Thanks in advance.
var firstList:Array = getWordsArrayFromTextFile("first.txt");
var secondList:Array = getWordsArrayFromTextFile("second.txt");
var index:Number = Math.round(Math.random() * (firstList.length - 1));
firstword_txt.text = firstList[index];
secondword_txt.text = secondList[index];
function getWordsArrayFromTextFile(loc:String):Array{
var words:Array = new Array();
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, loading);
loader.load(new URLRequest(loc));
function loading (e:Event):void {
for(var c:Number = 0; c < loader.data.length; c++){
words.push(loader.data["var_" + c.toString()]);
}
}
return words; //Returns before complete event has finished, so words array is empty
}
Question
aberflasm
What I am trying to do is use a function for reading a textfile, storing the variables into an array, and then return the array. My problem is that I do not know how to wait for the arrays to be populated before returning them. (see code below)
This is my first attempt at working with Flash/Actionscript 3.0. I understand the async part but I am not sure if/how I can workaround it. Nothing that I have googled has provided me with any help. I need some clarity and am hoping someone here can help provide it! Thanks in advance.
var firstList:Array = getWordsArrayFromTextFile("first.txt"); var secondList:Array = getWordsArrayFromTextFile("second.txt"); var index:Number = Math.round(Math.random() * (firstList.length - 1)); firstword_txt.text = firstList[index]; secondword_txt.text = secondList[index]; function getWordsArrayFromTextFile(loc:String):Array{ var words:Array = new Array(); var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.addEventListener(Event.COMPLETE, loading); loader.load(new URLRequest(loc)); function loading (e:Event):void { for(var c:Number = 0; c < loader.data.length; c++){ words.push(loader.data["var_" + c.toString()]); } } return words; //Returns before complete event has finished, so words array is empty }Link to comment
Share on other sites
3 answers to this question
Recommended Posts