We've gone pretty far with our interpreter/compiler/vm setup, but we still can't handle 12+3. Let's fix that.
The line we want to replace is var result: i64 = @as(i64, input[input_pos]) - '0'; -- we need to eat the whole number, not just one digit. Wrap it in a helper. Single-digit for now; next problem you'll make it loop.
fn parseNumber(
buffer: []const u8,
position: *usize,
) i64 {
const value: i64 = @as(i64, buffer[position.*]) - '0';
position.* += 1;
return value;
}
In the interpreter, call parseNumber(input, &input_pos) in place of the two inline digit reads. The chain-loop condition is input[input_pos] != 0 -- input is [:0]const u8, so reading at input.len returns the sentinel 0 instead of going out of bounds.
Single-digit tests still pass.
var result: i64 = parseNumber(input, &input_pos);
while (input[input_pos] != 0) {
const op: u8 = input[input_pos];
input_pos += 1;
const next_number: i64 = parseNumber(input, &input_pos);
if (op == '+') {
result = result + next_number;
} else if (op == '-') {
result = result - next_number;
} else if (op == '*') {
result = result * next_number;
} else if (op == '/') {
result = @divTrunc(result, next_number);
} else {
printString("error: unknown operator\n");
return;
}
}
Renamed next_digit -> next_number since one problem from now it won't be a single digit.