Search code examples
actionscript-3actionscript

Syntax error: expecting semicolon before leftbracket


I have the following code at frame one of the top layer:

var level:Array = new Array();
var level[0] = new Object();

I am getting the following error:

Scene 1, Layer 'levels', Frame 1, Line 2
1086: Syntax error: expecting semicolon before leftbracket.

I've looked at many examples which seem to be doing the same thing I'm doing, and I've also tried defining the object separately and then adding it to the array, with the same error. I've also searched for the answer, but all the questions I've found are a little different than this situation.


Solution

  • The syntax/grammar production

    var level[0] = new Object();
    

    is invalid.

    The var production expects a simple Identifier, not an expression1. The parser was roughly trying to treat the production as var level;[0] = ..; (but failed due to the missing semicolon, and would have failed anyway because [0] = ..; is an invalid production as well).

    Try:

    var level:Array = new Array();
    level[0] = new Object(); // no "var" here so it is a valid grammar production
    

    or, more concisely:

    var level:Array = [{}];  // using Array and Object literal notations
    

    1 See AS3.g for that ANTLR production rules. Alternatively, for ECMAScript (from which AS derives), see 12.2 Variable Statement from ES5-Annotated and note that it requires an "Identifier" followed by an optional initializer (=) or another declaration (,) or end of statement (;).