Hi Keith!

[EMAIL PROTECTED] 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.

Actually, C is global by default too. Most block-structured
languages are, even ones with a single level of nesting like
C (and Perl?). The trick here is to notice where the variable
is _declared_, rather than where it is first referenced.

The only difference here is that you can declare new variables
inside the block in C while you declare them outside the block
in REBOL, except for in object! specs.

For example, in C:
{
     int i;  /* The declaration (with type) */
     i = 2;  /* An assignment */
     i + 1;  /* A reference */
}
/*
   Declaration is associated with code block by compiler.
*/

is equivalent to this in REBOL:
use [i] [   ; The declaration (without type)
     i: 2    ; An assignment
     i + 1   ; A reference
]
; Declaration is performed by use native! at runtime.

The only difference comes from C being a static language,
requiring declarations for all variables (ANSI C), while
REBOL only requires declarations of local variables to
distinguish them from the global. In C, undeclared words
are considered to be declared elsewhere in the global
context, with the final determination made by the linker.
C has to do this because its variables are typed. REBOL
adds undeclared words to the global context at runtime,
something it can do because its words can take values of
any type.

How this all happens doesn't matter for these purposes,
way too in-depth. I've found that you don't need to know
the internals of REBOL scoping unless you are doing stuff
that doesn't obey the scope rules. That doesn't happen as
often as you think in REBOL code - most code behaves as
you would expect. All code, with enough experience... ;)

>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.

I guess that PHP isn't a block-structured language then.
It would be interesting to study this language so as to
understand why this approach is appropriate (if it is).

Brian Hawley

Reply via email to