In fact in many languages - including every version of Lisp before Scheme and Perl before my was introduced in Perl 5 - dynamic scope was routinely used for what we now tell people to use lexical scope for.
That would be a grave mistake. If
that is true, then I can certainly see why you would
be hesitant about the use of dynamic scope; it is
clearly inappropriate for avoiding namespace clashes.
That wouldn't work very well at all; there would be
all sorts of hard-to-debug problems if it were used
for that. However, that doesn't mean dynamic scope
isn't useful, or even that it's less useful than
lexical scope; it only means it's not useful for the
same kinds of things.
And there are times when you really do
want dynamic scope. But those are few and far
between.
I can't agree with that. When you understand dynamic
scope properly (i.e., are using it for what it's good
for, not as some kind of warped substitute for lexical
scope), it's very useful indeed.
If you need to simulate lexical scope in a language
that doesn't support it directly, the right way to
do that is by naming convention (i.e., name your
lexical variables starting with the name of the
package (and possibly routine) that contains them),
not by misusing dynamic scope.
But it's also not appropriate to try to use lexical
scope as a substitute for dynamic scope; that would
be at least as hideously inappropriate, if it could
even be made to work at all.
And no, most of the time you aren't going to be
dynamically scoping lots and lots of variables.
But the ones that you do need to scope that way,
you need to scope that way. As
you point out, trying to work around a lack of
it is nightmarish. Yeah, it can be done -- in the
same sense that recursion can be done in languages
like line number BASIC that don't support passing
parameters to subroutines. (I did this once. It
was kinda fun, actually, in a perverse sort of way.
I used a set of parallel arrays to simulate a stack,
which I pushed my values onto before GOSUB (to save
them) and then popped them off of after the routine
RETURNed. It was messy, though, and fun only as
an exercise, and I don't want to do it again.)
for(unpack("C*",'GGGG?GGGG?O__\?WccW?{GCw?Wcc{?Wcc~?Wcc{?~cc'
.'W?')){$j=$_-63;++$a;for$p(0..7){$h[$p][$a]=$j%2;$j/=2}}for$
p(0..7){for$a(1..45){$_=($h[$p-1][$a])?'#':' ';print}print$/}
|