Loops

From Onix OS Wiki
Jump to: navigation, search

Loops are very strange things. They will keep working until you say stop. After you have learned this, you may have taken part in many cycles.

Like a life cycle. You work every day, but at the end of the day you want to reach the conclusion. And when the day of payment comes, your goal is to pay for the days you work. In this way, you will continue to function as a worker in the life cycle as long as you receive money.

Definition

There are two types of loops. These are "Loop()" and "for()" depending on how you use them. Let's take a look at two loop variants with a little more detailed analysis.

loop()

loop(...when is it true...){
....work with definitions...
}

The result in the function continues to do its job until the correct result is returned. It's usually double-sided. It either continues until a number is greater than one or smaller. Otherwise, the loop ends automatically when a situation returns true.

Example

def i = 0;
loop(i>100){ 
  println(i);
  def i = (i+1);
}

# => 0
# => 1
# => 2
# => 3
# => ....
# => 99

We have defined an "I" in the example and we have adjusted it to zero. Next, we say "I" and when it is closer to being larger than 100, IT returns true and the loop ends. That's simple.

for()

for("some array" in key,value){
....work with key and value...
}
for("some hash" in key,value){
....work with key and value...
}

The use of "for()" here is very different. Puts all elements in the specified first object into a loop by equalizing them as a key and value. The loop automatically terminates when the key and value within the item run out.

Example

def arr = [1,2,3,4,5]
for(arr in k,v){
  println(v)
}

# => 1
# => 2
# => 3
# => 4
# => 5
def arrtwo = {"one":1, "two":2};
for(arrtwo in k,v){
  println(k)
  println(v)
}

# => one
# => 1
# => two
# => 2

In the first example, we loop through the array "arr" and display all the values in it. In the second loop, we list all the keys and values in a hash object so that the key first appears.