Search code examples
parsingrebolrebol3

Howto make local word assignment inside PARSE in REBOL?


I need a function that uses PARSE and the COPY x rule, but does not change x outside the function. I tried to use FUNCTION to have it automatically pick up the local x, but it does not work:

>> f: function [t] [parse t [copy x to end]]
>> f ["a"]
== true
>> print x
a

Solution

  • With your FUNCTION use, you're already halfway there. You can combine two recent changes:

    1. FUNCTION automatically gathers all set-word!s used in the body as local variables.
    2. The COPY and SET rules of PARSE have been relaxed to also accept set-word!s as their first argument.

    So that'd give you:

    ;; Note the subtle change of `x` to `x:` compared to your original version:
    >> f: function [t] [parse t [copy x: to end]]
    
    >> f ["a"]
    == true
    
    >> x
    ** Script error: x has no value
    

    Alternatively, you can also explicitly list your local variables using the /local convention:

    >> f: function [t /local x] [parse t [copy x to end]]
    >> f ["a"]
    >> x
    ** Script error: x has no value