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.,
ainsidefunc-2would be bound to the top-levela) - Run-time: When
a: 1is executed, the value1is stored in thea's slot in the context. - The
funckeyword afterfunc-1:creates a new function, and assigns it tofunc-1. However, it leaves the binding ofaintact. - The
contextkeyword afterinner:creates a new context B, walks over all the block, collecting all new symbols, and inserts those in the new object. a: 2assigns value2ina's slot in the new context.funcafterfunc-2:creates a function while keepinga's new binding intact, and assigns it tofunc-2's slot.funcafterfunc-3:creates a function and creates a new context C in whichais inserted and bound.- Upon execution of
reduce,func-1returns1from context A,func-2return2from context B, andfunc-3executesfunc-1which returns1from context A again.
So, now, a few questions:
- Is the above correct? If it is,
- How does the
contextkeyword determine which set-words it should create a slot for? i.e.,- if
a: 2didn't exist, will it still create the slot foradue toa: 3deep inside? - What about if
a:3didn't exist either? Will the new context contain a slot forajust due toainsidefunc-2's body?
- if
- Did
contextbindain[/local a]too, beforefuncwas 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.