Announcement

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

  • locals vs. scalars

    There is an interesting current thread on Twitter about the use of locals vs. scalars. Stata experts won't be surprised with the content, but those with lower levels of expertise (e.g. me) may find this to be a particularly valuable reminder.

    The thread is at https://twitter.com/nomadj1s/status/1143505196775104512

    The thread's essence is
    Code:
    . do "/var/folders/d5/6w9t_lzx3plbpmk6zpyz93dm0000gp/T//SD05991.000000"
    
    . local j=-2
    
    . di `j'
    -2
    
    . local i=`j'^2
    
    . di `i'
    -4
    
    . local i=(`j')^2
    
    . di `i'
    4
    
    . scalar k=-2
    
    . di k
    -2
    
    . di k^2
    4
    
    .
    end of do-file

  • #2
    This is a good thing to know. As i use local over scalar alot more than a should.

    Thanks

    Comment


    • #3
      The topic on the Twitter thread was covered here on Statalist at roughly the same time in response to a user's question at the following topic, but the good news was that Clyde Schechter gave a brief and comprehensive explanation in post #2. It seems to me I had to go fairly deep into the Twitter thread to find a similar level of understanding.

      https://www.statalist.org/forums/for...ts-calculation

      Also, taking the code from post #1 and running it with trace on shows us the statements Stata constructs when the macros are dereferenced.
      Code:
        - local j=-2
        - display `j'
        = display -2
      -2
        - local i=`j'^2
        = local i=-2^2
        - display `i'
        = display -4
      -4
        - local i=(`j')^2
        = local i=(-2)^2
        - display `i'
        = display 4
      4
        - scalar k=-2
        - display k
      -2
        - display k^2
      4

      Comment


      • #4
        Thanks William. I'll post your and Clyde's helpful responses in the Twitter thread.

        Comment


        • #5
          We could (should!) also mention that this has been a FAQ since whenever: https://www.stata.com/support/faqs/p...ower-operator/ (search gives a 2015 date, but that's just to the latest revision; I think this FAQ goes back to around 2000).

          The key is that local macros contain text and macro references are evaluated -- and the corresponding text inserted in a command (which includes the case of empty text, whenever the macro doesn't exist) -- before anything else is done.


          Comment

          Working...
          X