-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathinterpreter.zig
More file actions
68 lines (56 loc) · 2.28 KB
/
interpreter.zig
File metadata and controls
68 lines (56 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! Simple Lua interpreter
//! This is a modified program from Programming in Lua 4th Edition
const std = @import("std");
// The zlua module is made available in build.zig
const zlua = @import("zlua");
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
// Initialize The Lua vm and get a reference to the main thread
//
// Passing a Zig allocator to the Lua state requires a stable pointer
var lua = try zlua.Lua.init(allocator);
defer lua.deinit();
// Open all Lua standard libraries
lua.openLibs();
var in_buf: [1024]u8 = undefined;
var out_buf: [4096]u8 = undefined;
var stdin_file = std.fs.File.stdin().reader(&in_buf);
const stdin = &stdin_file.interface;
var stdout_file = std.fs.File.stdout().writer(&out_buf);
const stdout = &stdout_file.interface;
while (true) {
_ = try stdout.writeAll("> ");
try stdout.flush();
// Read a line of input
const line = stdin.takeDelimiterInclusive('\n') catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
if (line.len == 0) break; // EOF
if (@intFromPtr(line.ptr) + line.len >= @intFromPtr(&in_buf) + in_buf.len) {
try stdout.print("error: line too long!\n", .{});
continue;
}
// Ensure the buffer is null-terminated so the Lua API can read the length
line.ptr[line.len] = 0;
// Compile a line of Lua code
lua.loadString(line.ptr[0..line.len :0]) catch {
// If there was an error, Lua will place an error string on the top of the stack.
// Here we print out the string to inform the user of the issue.
try stdout.print("{s}\n", .{lua.toString(-1) catch unreachable});
try stdout.flush();
// Remove the error from the stack and go back to the prompt
lua.pop(1);
continue;
};
// Execute a line of Lua code
lua.protectedCall(.{}) catch {
// Error handling here is the same as above.
try stdout.print("{s}\n", .{lua.toString(-1) catch unreachable});
try stdout.flush();
lua.pop(1);
};
}
}