Skip to main content
Inspiring
October 2, 2013
Answered

AS3 syntax question

  • October 2, 2013
  • 2 replies
  • 678 views

Hi,

Having a syntax problem/question. When I write this in AS3, I get the correct result: 4

          var wordArray1:Array = ["test","apple","orange","olive"];

          var theLevel:Number = 1;

 

          trace(root["wordArray" + theLevel].length);

but when I write it this way, inside a function, I get an error:

function test():void

{

          var wordArray1:Array = ["test","apple","orange","olive"];

          var theLevel:Number = 1;

 

          trace(root["wordArray" + theLevel].length);

}

test();

I can't understand what I'm doing wrong? Any ideas?

This topic has been closed for replies.
Correct answer moccamaximum

in the second case wordArrays scope is limited to the function.

so when you try to adress wordArray with root.wordArray, the main timeline doesn`t know about it.

simple fix: declare it outside of the function.

var wordArray1:Array;

function test():void

{

          wordArray1= ["test","apple","orange","olive"];

          var theLevel:Number = 1;

 

          trace(root["wordArray" + theLevel].length);

}

test();

2 replies

sinious
Legend
October 2, 2013

Here's an Adobe article you should briefly read to understand variable scope to solve any future headaches:

http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9d.html

moccamaximumCorrect answer
Inspiring
October 2, 2013

in the second case wordArrays scope is limited to the function.

so when you try to adress wordArray with root.wordArray, the main timeline doesn`t know about it.

simple fix: declare it outside of the function.

var wordArray1:Array;

function test():void

{

          wordArray1= ["test","apple","orange","olive"];

          var theLevel:Number = 1;

 

          trace(root["wordArray" + theLevel].length);

}

test();

Inspiring
October 2, 2013

Thank you so much. That resolved the problem right away!