FOREACH on objects
Here's a common coding pattern: iterating over the words (and values) of an object:
foreach word words-of my-object [
do-something-with word
]
The suggestion was made to support such a loop directly:
foreach word my-object [
do-something-with word
]
and also allow:
foreach [word value] my-object [
do-something-else-with word value
]
The benefit is that no intermediate block of words is constructed.
This change has been added to the A49 release.
Examples:
>> foreach word system/options [?? word]
word: boot
word: home
word: path
word: flags
word: script
word: args
word: do-arg
word: import
word: debug
word: secure
word: version
word: quiet
word: binary-base
word: decimal-digits
word: module-paths
word: file-types
Note that the word is bound back to the object, so can be used to access the value (with get).
However, it also supports:
>> foreach [word value] system/options [print [word mold value]]
boot %/C/rebol/r3/make/view/Debug/view.exe
home %/C/rebol/r3/make/
path %/C/rebol/r3/make/view/Debug/
flags [true]
script none
args none
do-arg none
import none
debug none
secure none
version none
quiet false
binary-base 16
decimal-digits 15
module-paths [%./]
file-types [%.bmp bmp %.gif gif %.png png %.jpg %.jpeg jpeg]
Be careful with hidden (protected) variables. The loop will skip them:
>> foreach word system/state [?? word]
word: note
word: last-error
The state object contains more than two fields, but they are not accessible to user code for security reasons.
5 Comments
|