kota's memex

if

Zig's basic if statement only accepts a bool value. There's no concept of truthy or falsy values.

const a = true;
var x: u16 = 0;
if (a) {
    x += 1;
} else {
    x += 2;
}

inline

const a = true;
var x: u16 = 0;
x += if (a) 1 else 2;

while

Zig's while loop has three parts - a condition, a block, and a continue expression.

without continue

var i: u8 = 2;
while (i < 100) {
    i *= 2;
}

with continue expression

var sum: u8 = 0;
var i: u8 = 1;
while (i <= 10) : (i += 1) {
  sum += i;
}

with continue inside loop

var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
    if (i == 2) continue;
    sum += i;
}

with break inside loop

var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
    if (i == 2) break;
    sum += i;
}
try expect(sum == 1);

for

For loops are used to iterate over arrays (and other such types). Like, while, for loops can use break and continue. Here I've assigned values to _ as zig does not allow usused values.

//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };

for (string, 0..) |character, index| {
    _ = character;
    _ = index;
}

for (string) |character| {
    _ = character;
}

for (string, 0..) |_, index| {
    _ = index;
}

for (string) |_| {}

capture

The syntax |x| is called a capture. It's used to capture an iteration value and give it a name.

https://kristoff.it/blog/zig-multi-sequence-for-loops/