New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
for loop can't use an existing variable #1935
Comments
There's a problem with the scoping here; my reading of the documentation says that it should behave as you expect. |
In the meantime, this is a workaround. for _index in (seq $index $count)
set index $_index
...
end |
for loops have historically used local scope like |
Not to say that changing this behaviour may be incompatible change, as people may have depended on current behavior by for example reusing identifiers in a loop. use 5.012;
my $i = 5;
for $i (1..3) {
say $i;
}
say $i; >>> i = 5
>>> [i for i in range(1, 4)]
[1, 2, 3]
>>> i
5
>>> As for workaround if you need last value in the loop, it's quite easy. Just assign it to unscoped variable. set -l last
for index in (seq 10)
set last $index
echo $index
end
echo $last |
I would love this: for set -l index 1 in (seq 10)
echo $index
end In the same vein of: if set -l result (get_data)
# ...
end |
I know that fish is not a Bourne shell and doesn't have to be compatible with anything else. However, I think it is useful to compare it to other shells' behavior. All other things being equal, consistency is good. Is there a good reason for fish to be different in this important way?
|
No. I think we'd take a fix. |
There is another reason to put the var in the enclosing scope. If you break out of the loop early it makes it possible to easily detect without having to introduce yet another var. However, this could only be changed in a major release and ideally we'd like to do more than one incompatible change if we're going to go to the trouble of making a major release. |
Following up on my earlier comment about being consistent with other shells, this is interesting. This is rc by Byron Rakitzis via debian package "rc" 1.7.2-1:
This is rc by Tom Duff from Plan 9 from User Space:
|
You can fix this by cherry-picking commit cc3692fb from https://github.com/krader1961/fish. |
That's weird. I did not expect that fixing this in my fork would close this issue. I'll be more careful in the future about mentioning issues in this fork. |
* Hoist `for` loop control var to enclosing scope It should be possible to reference the last value assigned to a `for` loop control var when the loop terminates. This makes it easier to detect if we broke out of the loop among other things. This change makes fish `for` loops behave like most other shells. Fixes #1935 * Remove redundant line
I thought
$index
would exit thefor
loop with 10 since I declared$index
outside the loop. Why?The text was updated successfully, but these errors were encountered: