That's a great question! We should put it in our FAQ (ping: Bo). There are two answers:
1) Because it's easier for beginners:
During design I considered scoping both ways, top down (non-local default) and bottom
up (local default). Problem is, defaulting non-local is much easier for beginners and
for writing those quickie scripts.
Consider this: if local is the preferred scope, then every non-local word must be
declared. That would require *every* REBOL function name that is used in the function
to be declared.
2) You can have it your way:
The beauty of REBOL is that you can write your own function for creating functions
where local variables are the default. This is possible because REBOL uses
Definitional Scoping - a dynamic form of static scoping that depends on context
Is such a function difficult to write? No. Consider the fact that the func function
you use everyday is only one line of REBOL:
func: make function! [args body] [make function! args body]
To create a revfunc (reversed scoped) function, you will need to scan body and all of
its sub-blocks to build a list of words. You would then remove from that list all
words that are declared as non-locals. Here is the code, using the function function
to hold the locals block:
revfunc: func [args nonlocals body] [
function args find-all-words body nonlocals body
Find-all-words is left as an exercise to readers so that they will remember this
At 7/18/00 09:49 PM -0400, you wrote:
>I've been wondering what the reasoning behind REBOL's scoping rules was for
>awhile. In C, for instance, any variable that you declare in a function is
>"automatic" (that's what C calls them anyway :). They're automatically local
>to the function they're defined in, etc.
>Why does REBOL have variables be globally scoped by default? I ran into this
>a few days ago when I asked the list for assistance, and people helpfully
>replied (thank you). One of the things people pointed out was that I wasn't
>being careful with my recursion and kept using the same global variable over
>and over again.
>Perl takes a similar approach, where everything is global unless you declare
>the variable 'local' or 'my', but I always assumed that this was just
>because of Perl's heritage as a "throw away" script language, in which cases
>you really don't have to worry about scoping so much.
>PHP takes a completely opposite approach. Any variable you declare is local
>to a function, and you can't even get at global variables unless you
>explicitly get the variable through the $GLOBALS associative array, or
>declare a variable 'global' in your function.
>Anyway, I'd really like to understand why REBOL works the way it does in
>this respect, so if anyone has any insight to give I'd love to receive it.
>Thanks so much.