Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search

[REBOL] Re: Variable not avilable out of a foreach

From: anton::wilddsl::net::au at: 12-Dec-2007 2:18

Hi Giuseppe, Let me just start by saying that rebol defines no "scope". Every word can be bound and rebound dynamically (completely unlike C.) rebol [] get_data: does [ parse line [] ] main_loop: does [ database: ["hello" "buon giorno"] foreach line database [ get_data ] ] main_loop
> The script returns LINE has no Value, I must assign it to a temporary > variable... why ? > > Giuseppe Chillemi
The foreach creates a temporary context for use during evaluation of its body block. You supplied a word, 'line, which is taken literally by foreach and added as a new word in the new, temporary context. The 'line word which is written right after 'foreach word is a completely independent word from the 'line which the foreach creates in its temporary context. (The 'line word inside the get_data function body is also a completely independent word from the 'line which the foreach creates in its temporary context.) The foreach then binds its body block to the new context. Nowhere in the above body block has the 'line word been written. All that is in the body block is: [get_data] a single word (and it is not 'line). Therefore, no words in the body block have their binding changed. In summary, the foreach created a new word in a "hidden" context, instead of using the 'line word from the global context. You could work around this by different methods: 1) Set a word which is not in the foreach temporary context. foreach row database [line: row get_data] 2) Modify the function to add a parameter so you can mention 'line when passing an argument. get_data: func [line][...] ... foreach line database [get_data line] 3) Modify the function body. get_data: does [...] ... foreach line database [ bind second :get_data 'line get_data ] 4) Make your own variety of foreach which does not create its own context but uses words with existing bindings. Regards, Anton.