views:

29

answers:

3

I have the following script that is calling a text file:

    /* first create a new instance of the LoadVars object */
myVariables = new LoadVars();
myVariables.load("myFile.txt");
myVariables.onLoad = function(getreading):String{
    var ODOMETER2:String=myVariables.ACADEMICWATER;
    return ODOMETER2;
    trace (ODOMETER2);
}
trace(getreading());

The text file contains the following:

ACADEMICWATER=3002&elec=89

I am able to import the value of 3002 into the fuction and I can trace it. However, I Should be able to trace it outside the function using trace(getreading()); as shown on the last line. This only returns an "UNDEFINED" value. I am stumped.

+1  A: 

You are declaring an anonymous function (see AS3 Syntax and language / Functions) which can't be referenced by name. getreading is declared in your code as an untyped parameter of this function.

If you want to trace the result of this function, then you should declare a named function like this:

function getReading(): String {
    var ODOMETER2:String=myVariables.ACADEMICWATER;
    return ODOMETER2;
}

myVariables.onLoad = getReading;

trace(getReading());
splash
A: 

getreading is not the name of the function in this case, but the name of a parameter to the anonymous function that is run on the onLoad event of the myVariables object.

Place the variable ODOMETER2 outside the function and set it's value inside the anonymous function. Then you will be able to access it outside the function as well.

/* first create a new instance of the LoadVars object */ 
var ODOMETER2:String;
myVariables = new LoadVars(); 
myVariables.load("myFile.txt"); 
myVariables.onLoad = function(){ 
    ODOMETER2=myVariables.ACADEMICWATER; 
} 
trace(ODOMETER2); 
Charlie boy
A: 

LoadVars.onLoad is an event handler. It is called by LoadVars as soon as it finishes with the asynchronous load operation. It takes a boolean argument, indicating success or failure of the operation. It does not return anything.

LoadVars.onLoad documentation

In that function, you typically act upon the data you received, like storing and processing it. Here's a very simple example showing some basic use cases:

var ODOMETER2:String;

var myVariables = new LoadVars();
myVariables.load("myFile.txt");
myVariables.onLoad = function(success) {
    trace(success);
    ODOMETER2 = myVariables.ACADEMICWATER;
    processResults();
}

function processResults() {
    trace(ODOMETER2);
    trace(myVariables.ACADEMICWATER);
}

// traces:
// true
// 3002
// 3002
Claus Wahlers

related questions