Search Unity

Scope of variables

Discussion in 'Scripting' started by mkolb, Feb 27, 2008.

  1. mkolb

    mkolb

    Joined:
    Dec 17, 2007
    Posts:
    48
    Hi,

    I just came across a quite strange issue which is not logical to me at all.

    Code (csharp):
    1.  
    2. if (true) {
    3.         var duplicate : int = 0;
    4.     }
    5.     else if (false) {
    6.         var duplicate : int = 0;
    7.     }
    8.  
    That code throws an error in Unity, "There is already a local variable with the name 'duplicate'".
    Are the variable scopes in JavaScript different than in C#?
    If yes, I would really be surprised

    Regards
     
  2. NYGhost

    NYGhost

    Joined:
    Sep 20, 2007
    Posts:
    55
    I had the same problem when I started.
    the scope of the local variables seem to be function wide.
    logically they should be block wide.

     
  3. Jonathan Czeck

    Jonathan Czeck

    Joined:
    Mar 17, 2005
    Posts:
    1,713
    Welcome to the sometimes twisted world of UnityScript/JavaScript. It's working as intended, apparently. I hate the behavior.

    -Jon
     
  4. mkolb

    mkolb

    Joined:
    Dec 17, 2007
    Posts:
    48
    That's just odd, odd, odd...

    Can anyone from OTEE point out why it is that way?

    Regards
     
  5. Aras

    Aras

    Unity Technologies

    Joined:
    Nov 7, 2005
    Posts:
    4,770
    Yes, it's very odd. It's also the way JavaScript language standard is defined.