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>
string language = "zephir"; char ch;
for ch in language { echo "[", ch ,"]";}`</pre>
按相反顺序:
string language = "zephir"; char ch;
for ch in reverse language {
echo "[", ch ,"]";
}
遍历一系列整数值
可以写成如下:
for i in range(1, 10) {
echo i, "\n";
}
要避免对未使用的变量发出警告,可以在
for
语句中使用匿名变量,方法是使用占位符` _ </ 0>替换变量名称:</p>
使用键, 但忽略该值
for key, _ in data { echo key, "\n";}`</pre>
Break 语句
break
结束当前while
、for
或loop
语句的执行:
for item in ["a", "b", "c", "d"] {
if item == "c" {
break; // exit the for
}
echo item, "\n";
}
Continue 语句
在循环结构中使用
continue
跳过当前循环迭代的其余部分, 并在条件计算时继续执行, 然后在下一次迭代的开始时继续执行。
let a = 5;
while a > 0 {
let a--;
if a == 3 {
continue;
}
echo a, "\n";
}