Loops

While 语句

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

let counter = 5;
while counter {
    let counter -= 1;
}

Loop 语句

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

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

For 语句

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

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

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

let items = ["a": 1, "b": 2, "c": 3, "d": 4];

for key, value in items {
    echo key, " ", value, "\n";
}

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

let items = [1, 2, 3, 4, 5];
for value in reverse items {    echo value, "\n";}`</pre>
` for </ 0>循环可用于遍历字符串变量:</p>
  • for ch in language {    echo "[", ch ,"]";}`</pre>
  • 按相反顺序:
  • string language = &#34;zephir&#34;; char ch;
  • for ch in reverse language {
  •     echo &#34;[&#34;, ch ,&#34;]&#34;;
  • }
  • 遍历一系列整数值
  • for i in range(1, 10) {
  •     echo i, &#34;\n&#34;;
  • }
  • 要避免对未使用的变量发出警告,可以在for
  • 使用键, 但忽略该值
  • for key, _ in data {    echo key, "\n";}`</pre>
  • Break 语句break
    while
    for
    loop
  • for item in [&#34;a&#34;, &#34;b&#34;, &#34;c&#34;, &#34;d&#34;] {
  •     if item == &#34;c&#34; {
  •         break; // exit the for
  •     }
  •     echo item, &#34;\n&#34;;
  • }
  • Continue 语句在循环结构中使用 continue
  • let a = 5;
  • while a &gt; 0 {
  •     let a--;
  •     if a == 3 {
  •         continue;
  •     }
  •     echo a, &#34;\n&#34;;
  • }