Skip to content

Commit f05e11e

Browse files
committed
fix(examples): update examples/interpreter.zig to Writergate
closes #167
1 parent 317bfbe commit f05e11e

1 file changed

Lines changed: 12 additions & 7 deletions

File tree

examples/interpreter.zig

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,33 +20,37 @@ pub fn main() anyerror!void {
2020
// Open all Lua standard libraries
2121
lua.openLibs();
2222

23-
var in_buf: [4096]u8 = undefined;
23+
var in_buf: [1024]u8 = undefined;
2424
var out_buf: [4096]u8 = undefined;
2525
var stdin_file = std.fs.File.stdin().reader(&in_buf);
2626
const stdin = &stdin_file.interface;
2727
var stdout_file = std.fs.File.stdout().writer(&out_buf);
2828
const stdout = &stdout_file.interface;
2929

30-
var buffer: [256]u8 = undefined;
3130
while (true) {
3231
_ = try stdout.writeAll("> ");
32+
try stdout.flush();
3333

3434
// Read a line of input
35-
const len = try stdin.readSliceShort(&buffer);
36-
if (len == 0) break; // EOF
37-
if (len >= buffer.len - 1) {
35+
const line = stdin.takeDelimiterInclusive('\n') catch |err| switch (err) {
36+
error.EndOfStream => break,
37+
else => return err,
38+
};
39+
if (line.len == 0) break; // EOF
40+
if (@intFromPtr(line.ptr) + line.len >= @intFromPtr(&in_buf) + in_buf.len) {
3841
try stdout.print("error: line too long!\n", .{});
3942
continue;
4043
}
4144

4245
// Ensure the buffer is null-terminated so the Lua API can read the length
43-
buffer[len] = 0;
46+
line.ptr[line.len] = 0;
4447

4548
// Compile a line of Lua code
46-
lua.loadString(buffer[0..len :0]) catch {
49+
lua.loadString(line.ptr[0..line.len :0]) catch {
4750
// If there was an error, Lua will place an error string on the top of the stack.
4851
// Here we print out the string to inform the user of the issue.
4952
try stdout.print("{s}\n", .{lua.toString(-1) catch unreachable});
53+
try stdout.flush();
5054

5155
// Remove the error from the stack and go back to the prompt
5256
lua.pop(1);
@@ -57,6 +61,7 @@ pub fn main() anyerror!void {
5761
lua.protectedCall(.{}) catch {
5862
// Error handling here is the same as above.
5963
try stdout.print("{s}\n", .{lua.toString(-1) catch unreachable});
64+
try stdout.flush();
6065
lua.pop(1);
6166
};
6267
}

0 commit comments

Comments
 (0)