Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • local definition distinguish and its calculation

    Occasionally, I got to learn the difference between [local] & [local =]. See the following code, any explanation or discussion is welcome.
    Code:
    local i=-2-8
    dis `i'
    dis `i'^2
    local j="-2-8"
    dis `j'
    dis `j'^2
    
    local i=-2-8
    local j -2-8
    dis `i'^2
    dis `j'^2
    The results:
    Code:
    local i=-2-8
    
    . dis `i'
    -10
    
    . dis `i'^2
    -100
    
    . local j="-2-8"
    
    . dis `j'
    -10
    
    . dis `j'^2
    -66
    
    .
    . local i=-2-8
    
    . local j -2-8
    
    . dis `i'^2
    -100
    
    . dis `j'^2
    -66
    
    .
    2B or not 2B, that's a question!

  • #2
    When you run
    Code:
    local i = expression
    the expression is evaluated and the result of the evaluation is saved in local macro i.

    When you run
    Code:
    local j expression
    without the =, the expression is not evaluated: it is copied as a string into local macro j.

    When you run
    Code:
    local k "expression"
    with quotation marks, the expression is not evaluated, it already is a string and it is copied as such into local macro k.

    Now let's see what Stata sees when you use these:

    Code:
    local i = -2-8
    display `i'^2
    translates to
    display -10^2
    which is -100
    Code:
    local j -2-8
    display `j'^2
    translates to
    display -2-8^2
    which evaluates, by the usual order of operations, to -2 - 64 = -66
    And local macro k also evaluates the same as local macro j.

    Comment


    • #3
      To Clyde's advice I would add that because the display command attempts to evaluate expressions it detects in its arguments, the macro list command is the best way of finding out exactly what the contents of a local or global macro are stored as.
      Code:
      . local i=-2-8
      
      . macro list _i
      _i:             -10
      
      . dis `i'^2
      -100
      
      . dis (`i')^2
      100
      
      . local j="-2-8"
      
      . macro list _j
      _j:             -2-8
      
      . dis `j'^2
      -66
      
      . dis (`j')^2
      100
      
      .
      . local i=-2-8
      
      . macro list _i
      _i:             -10
      
      . local j -2-8
      
      . macro list _j
      _j:             -2-8
      
      . dis `i'^2
      -100
      
      . dis `j'^2
      -66
      
      .

      Comment


      • #4
        As always, many thanks to Clyde's crystal clear explanation and William's further advice .
        2B or not 2B, that's a question!

        Comment

        Working...
        X