Skip to content
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 ... else #49

Closed
odino opened this issue Dec 21, 2018 · 2 comments
Closed

for ... else #49

odino opened this issue Dec 21, 2018 · 2 comments
Labels
enhancement New feature or request
Milestone

Comments

@odino
Copy link
Collaborator

odino commented Dec 21, 2018

No description provided.

@odino odino added the enhancement New feature or request label Dec 21, 2018
@odino odino added this to the future milestone Dec 21, 2018
@odino odino modified the milestones: cauldron, 1.3.x Feb 21, 2019
@mingwho
Copy link
Contributor

mingwho commented Feb 27, 2019

Will for... else work with both For and For In expression?
Something like these

for i in 0..-1 {
    echo("inside for")
} else {
    echo("inside else")
}

for i = 0; i < 10; i++ {
    if i == 11 { echo ("inside for") } 
} else {
        echo("inside else")
}

@odino
Copy link
Collaborator Author

odino commented Feb 27, 2019

I think for in is enough. The basic idea is to run some code if list in the for in is empty

users = db.query("SELECT students WHERE age > 20")

for user in users {
  print(user)
} else {
  print("We don't have students above the age of 20")
}

which you would have to write like this without for else:

users = db.query("SELECT students WHERE age > 20")

if users.len() {
  for user in users {
    print(user)
  }
} else {
  print("We don't have students above the age of 20")
}

or

users = db.query("SELECT students WHERE age > 20")

if users.len() {
  for user in users {
    print(user)
  }

  return
}
 
print("We don't have students above the age of 20")

BTW python does this differently (the else runs when there's no break), but I believe it'd be more useful to keep for ... else for other use cases. Jinja does this (even though it's a templating language):

<ul>
{% for user in users %}
    <li>{{ user.username|e }}</li>
{% else %}
    <li><em>no users found</em></li>
{% endfor %}
</ul>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants