giuliolunati
giuliolunati

Reputation: 766

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

Upvotes: 3

Views: 116

Answers (2)

earl
earl

Reputation: 41755

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

Upvotes: 3

ingo
ingo

Reputation: 521

Or, alternatively, you could use a set-word! in the function, but outside of parse.

>> f: function [t] [x: none c: charset [#"a" -#"] parse t [copy x some c] print x]
>> f "a"
a
>> x
** Script error: x has no value

While this has more overhead than the other alternatives, it may be helpful in debugging, if used like this:

>> f: function [t] [x: 10101 c: charset [#"a" -#"z"] parse t [copy x some c] print x]
>> f ""
10101

This makes it obvious, that the rule did not catch anything.

Upvotes: 2

Related Questions