Oct 11, 2013

vJASS for mules #7: Scope

Scope
In the previous lesson, we talked about that strange keyword: "static". What the hell is it?


Well, it was said that a object has it own attributes. But sometimes, there are attributes that own to the struct, not to the object. They are called "static". Example: A dog's number of eyes. It always two (ignores the anomalies). So it doesn't change from dog to dog. It's always STATIC.
The same principle is applied to static methods. Those are method that don't need a instance or object to be called, they can be called throught the struct name. Example:

struct ExampleOfStatic
    static integer numberOfEyes = 2
    static method create takes nothing returns thistype
        thistype this = thistype.allocate()
        set thistype.numberOfEyes = 3
        return this
    endmethod
endstruct

ExampleOfStatic var = ExampleOfStatic.create()

Since "create" is a static method, we call it throught the struct name. See the "thistype" keyword. Since "numberOfEyes" is a static attribute, we refference to it using "thistype" instead of "this". The thistype keyword also is used to refference to static methods. See the "thistype.allocate()" part. We can all replace "thistype" for simply the struct's name. Example:

struct ExampleOfStatic
    static integer numberOfEyes = 2
    static method create takes nothing returns thistype
        ExampleOfStatic this = ExampleOfStatic.allocate()
        set ExampleOfStatic.numberOfEyes = 3
        return this
    endmethod
endstruct

You got it now, don't you?

The "local" keyword
What is a argument? It's a variable that only exists inside a function. That exactly what "local" variable are, with the difference that they are created inside the code block of a function instead of in the argument list. See the example:

method bark takes nothing returns string
    local string sound = "au au"
    return sound
endmethod

Simple, isn't it?
Important note: All the local variables must be in the top of code block. Example:

method bark takes nothing returns string
   call something()
   local string sound = "au au"
   return sound
endmethod

It will throw an error. The correct syntax is:

method bark takes nothing returns string
   local string sound = "au au"
   call something()
   return sound
endmethod

So, in the end, we have now three levels of scope:


 


Answer mentally:

  • What is a static variable? 
  • What does "local" keyword do? 
  • What is thistype keyword? What its utility?

<<Previous>>                                                                                  <<Next>>


No comments :

Post a Comment