robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinlua: clean `lua_*` fn args & add `toRef` fn6507f5b

push-srxvuswpkqxx
2.2 KiB95 linesraw
1const std = @import("std");
2
3const fern = @import("fern");
4const zlua = @import("zlua");
5const Lua = zlua.Lua;
6
7const maivi = @import("../root.zig");
8
9pub fn lua_openstr(l: *Lua) !i32 {
10    l.createTable(0, 2);
11
12    l.pushFunction(zlua.wrap(len));
13    l.setField(-2, "len");
14
15    l.pushFunction(zlua.wrap(split));
16    l.setField(-2, "split");
17
18    l.pushFunction(zlua.wrap(escape));
19    l.setField(-2, "escape");
20
21    return 1;
22}
23
24pub fn len(l: *Lua) !i32 {
25    l.argCheck(l.isString(-1), -1, "string");
26
27    const str = try l.toString(-1);
28    const s = try maivi.allocator.dupe(u8, str);
29    defer maivi.allocator.free(s);
30
31    const str_len = try std.unicode.calcUtf16LeLen(str);
32    l.pushInteger(@intCast(str_len));
33
34    return 1;
35}
36
37pub fn split(l: *Lua) !i32 {
38    l.argCheck(l.isString(-2), -2, "string");
39    l.argCheck(l.isString(-1), -1, "string");
40
41    const str = try l.toString(-2);
42    const s = try maivi.allocator.dupe(u8, str);
43    defer maivi.allocator.free(s);
44
45    const sep_str = try l.toString(-1);
46    const sep = try maivi.allocator.dupe(u8, sep_str);
47    defer maivi.allocator.free(sep);
48
49    l.newTable();
50
51    var it = std.mem.splitSequence(u8, s, sep);
52    while (it.next()) |x| {
53        _ = l.pushString(x);
54
55        const index = l.lenRaw(-2) + 1;
56        l.setIndexRaw(-2, @intCast(index));
57    }
58
59    return 1;
60}
61
62pub fn escape(l: *Lua) !i32 {
63    l.argCheck(l.isString(-1), -1, "string");
64
65    const stack_size_on_entry = l.getTop();
66
67    const strz = try l.toString(-1);
68
69    var result: std.ArrayList(u8) = try .initCapacity(maivi.allocator, 0x100);
70    defer result.deinit(maivi.allocator);
71
72    for (strz) |char| {
73        const escaped: ?[]const u8 = switch (char) {
74            '<' => "&lt;",
75            '>' => "&gt;",
76            '&' => "&amp;",
77            '"' => "&quot;",
78            else => null,
79        };
80
81        if (escaped) |e|
82            try result.appendSlice(maivi.allocator, e)
83        else
84            try result.append(maivi.allocator, char);
85    }
86
87    const escaped = try result.toOwnedSlice(maivi.allocator);
88    defer maivi.allocator.free(escaped);
89
90    if (l.getTop() != stack_size_on_entry) return error.UnexpectedStackSize;
91
92    _ = l.pushString(escaped);
93
94    return 1;
95}