Hacker News new | past | comments | ask | show | jobs | submit login

True, lexical scoping is dominant in current programming languages and it is easier to reason about.

Alas Tcl is more complicated. It's sort of dynamic but not quite depending on how variables are accessed. For one thing a proc definition provides a separate scope from the global variable scope. If we define:

    set b 5 ;# global
    proc w {a} {
      # upvar 1 b b
      + $a $b ;# "can't read 'b': no such variable"
    }
    proc x {} {
        set b 2 ;# local
        w 0
    }
    x ;# error re: no such variable 'b'
If it was truly dynamic (or more correctly indefinite) scope, we'd see '2' printed because 'b' would be readable in procedure w, but instead we get an error. However if inside the procs '::b' was used instead of 'b', then 2 is printed consistent with dynamic scope. ('::b' is 'b' in the global namespace.)

Of course the call to w in x doesn't operate under lexical scope since procedures are global and can't access variables inside another procedure's scope.

It is possible under some conditions to mimic lexical scope using the upvar command. In the case of proc w, uncommenting the upvar call would reference var b in the calling proc (or stack frame).

Wow, written out that is kinda "mind-boggling"! But in practice it's not a problem keeping it straight, at least most of the time...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: