[REBOL] Re: Q: Functions and the visibility of words
From: ingo:2b1 at: 26-Apr-2001 12:10
... on default global variables [Sanghabum--aol--com] spoketh thus:
> The disadvantages are so major, that something needs to be done.
And here are two things I've come up with ...
context: func [
"Defines a unique (underived) object. *patched* (iho)"
blk [block!] "Object variables and values."
/globals
gwords [block!] "accessible words"
/local locals blk2 wrd
][
either globals [
locals: make block! 20
rule: [
any [
set wrd set-word! (
if not find gwords to-word :wrd [
append locals to-word :wrd
]
) |
into rule |
skip
]
to end
]
parse blk rule
forall gwords [ change gwords to-set-word first gwords]
blk2: compose/deep [ (head gwords) none use [(union locals locals)] [(blk)]]
] [
blk2: blk
]
make object! blk2
]
; testing ....
>> a: context [f: func [][ x: 1]]
>> x
** Script Error: x has no value
** Near: x
>> a/f
== 1
>> x
== 1
>> b: context/globals [g: func [][y: 1] h: func [][y]][g h]
>> b/g
== 1
>> b/h
== 1
>> y
** Script Error: y has no value
** Near: y
>>
; to be put around a whole script, only words in exports will show
; up in system/words ...
export: func [
"Only exports named words to the global context (iho)"
exports [block!] "block of words to export"
ctx [block!] "context block"
/local locals check rule wrd
] [
locals: make block! 20
check: func ['wrd [word!]][
if not find exports to-word get :wrd [
append locals to-word get :wrd
]
]
rule: [
any [
set wrd set-word! (check wrd) |
'set [
set wrd lit-word! (check wrd) |
into [any [set wrd word! (check wrd)]]
] |
into rule |
skip
]
to end
]
parse ctx rule
use union locals locals ctx
]
kind regards,
Ingo