Loops

While 语句

while denotes a loop that iterates as long as its given condition evaluates as true:

  1. let counter = 5;
  2. while counter {
  3. let counter -= 1;
  4. }

Loop 语句

除了 while, loop 还可用于创建无限循环:

  1. let n = 40;
  2. loop {
  3. let n -= 2;
  4. if n % 5 == 0 { break; }
  5. echo x, "\n";
  6. }

For 语句

for 是一种控制结构, 允许遍历数组或字符串:

  1. for item in ["a", "b", "c", "d"] {
  2. echo item, "\n";
  3. }

可以通过为键和值提供变量来获取哈希中的键:

  1. let items = ["a": 1, "b": 2, "c": 3, "d": 4];
  2. for key, value in items {
  3. echo key, " ", value, "\n";
  4. }

还可以指示` for </ 0>循环以相反的顺序遍历数组或字符串:</p>

  1. let items = [1, 2, 3, 4, 5];

  2. for value in reverse items { echo value, "\n";}`</pre>

  3. ` for </ 0>循环可用于遍历字符串变量:</p>

  4. string language = "zephir"; char ch;

  5. for ch in language { echo "[", ch ,"]";}`</pre>

  6. 按相反顺序:

  7. string language = &#34;zephir&#34;; char ch;
  8. for ch in reverse language {
  9.     echo &#34;[&#34;, ch ,&#34;]&#34;;
  10. }
  11. 遍历一系列整数值 可以写成如下:

  12. for i in range(1, 10) {
  13.     echo i, &#34;\n&#34;;
  14. }
  15. 要避免对未使用的变量发出警告,可以在for语句中使用匿名变量,方法是使用占位符` _ </ 0>替换变量名称:</p>

  16. 使用键, 但忽略该值
  17. for key, _ in data {    echo key, "\n";}`</pre> 

  18. Break 语句

    break 结束当前 whileforloop 语句的执行:

  19. for item in [&#34;a&#34;, &#34;b&#34;, &#34;c&#34;, &#34;d&#34;] {
  20.     if item == &#34;c&#34; {
  21.         break; // exit the for
  22.     }
  23.     echo item, &#34;\n&#34;;
  24. }
  25. Continue 语句

    在循环结构中使用 continue 跳过当前循环迭代的其余部分, 并在条件计算时继续执行, 然后在下一次迭代的开始时继续执行。

  26. let a = 5;
  27. while a &gt; 0 {
  28.     let a--;
  29.     if a == 3 {
  30.         continue;
  31.     }
  32.     echo a, &#34;\n&#34;;
  33. }