I just started learning Red/Rebol, and I was having trouble understanding the scoping rules. I did read the Stack Overflow and Bindology, and I think I somewhat understand, but I'm not sure! I'd be grateful if someone can confirm the my deductions about the following code from the SE post:
rebol []
a: 1
func-1: func [] [a]
inner: context [
a: 2
func-2: func [] [a]
func-3: func [/local a] [a: 3 func-1]
]
reduce [func-1 inner/func-2 inner/func-3]
-
Compile-time: First, when the code is compiled, a list of top-level names is created. (
a
,func-1
,inner
) -
Load-time: When the code is loaded, context A is created with those symbols as members. Also, the entire code is walked through, and every occurrence of those symbols is bound to these entries. (e.g.,
a
insidefunc-2
would be bound to the top-levela
) -
Run-time: When
a: 1
is executed, the value1
is stored in thea
's slot in the context. - The
func
keyword afterfunc-1:
creates a new function, and assigns it tofunc-1
. However, it leaves the binding ofa
intact. - The
context
keyword afterinner:
creates a new context B, walks over all the block, collecting all new symbols, and inserts those in the new object. -
a: 2
assigns value2
ina
's slot in the new context. -
func
afterfunc-2:
creates a function while keepinga
's new binding intact, and assigns it tofunc-2
's slot. -
func
afterfunc-3:
creates a function and creates a new context C in whicha
is inserted and bound. - Upon execution of
reduce
,func-1
returns1
from context A,func-2
return2
from context B, andfunc-3
executesfunc-1
which returns1
from context A again.
So, now, a few questions:
- Is the above correct? If it is,
- How does the
context
keyword determine which set-words it should create a slot for? i.e.,- if
a: 2
didn't exist, will it still create the slot fora
due toa: 3
deep inside? - What about if
a:3
didn't exist either? Will the new context contain a slot fora
just due toa
insidefunc-2
's body?
- if
- Did
context
binda
in[/local a]
too, beforefunc
was executed? - When a new context is created, does it copy existing symbols or bindings from the older context? If not,
- Is there a parent-child relationship between contexts, or are they free-standing? Given a context, can I chase some pointer to its parent or child?
Sorry for so many questions, I think I am getting extra confused since I already have programming experience and need to unlearn some stuff before being able to grok Rebol.
Thank you.