dotfiles/mzte-nv/src/ffi.zig

50 lines
1.6 KiB
Zig
Raw Permalink Normal View History

2022-10-18 23:03:39 +02:00
const std = @import("std");
pub const c = @cImport({
@cInclude("lua.h");
@cInclude("lualib.h");
2022-10-18 23:03:39 +02:00
@cInclude("lauxlib.h");
});
/// Generates a wrapper function with error handling for a lua CFunction
2023-07-29 10:44:55 +02:00
/// func should be `fn(*c.lua_State) !c_int` ()
pub fn luaFunc(comptime func: anytype) c.lua_CFunction {
2022-10-18 23:03:39 +02:00
return &struct {
fn f(l: ?*c.lua_State) callconv(.C) c_int {
return func(l.?) catch |e| {
2023-05-27 01:27:08 +02:00
var buf: [1024 * 4]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
fbs.writer().print("Zig Error: {s}\n", .{@errorName(e)}) catch @panic("OOM");
if (@errorReturnTrace()) |ert| {
std.debug.writeStackTrace(
ert.*,
fbs.writer(),
std.heap.c_allocator,
std.debug.getSelfDebugInfo() catch @panic("WTF"),
.no_color,
) catch @panic("OOM");
}
luaPushString(l, fbs.getWritten());
2022-10-18 23:03:39 +02:00
_ = c.lua_error(l);
unreachable;
};
}
}.f;
}
2023-02-21 21:42:55 +01:00
/// A thin wrapper around luaL_checklstring that uses the length parameter to return a slice.
2023-02-23 10:56:20 +01:00
pub fn luaCheckstring(l: ?*c.lua_State, idx: c_int) []const u8 {
2023-02-21 21:42:55 +01:00
var len: usize = 0;
return c.luaL_checklstring(l, idx, &len)[0..len];
}
2023-02-23 10:56:20 +01:00
pub fn luaPushString(l: ?*c.lua_State, s: []const u8) void {
2023-02-21 21:42:55 +01:00
c.lua_pushlstring(l, s.ptr, s.len);
}
2023-02-23 10:56:20 +01:00
pub fn luaToString(l: ?*c.lua_State, idx: c_int) []const u8 {
var len: usize = 0;
return c.lua_tolstring(l, idx, &len)[0..len];
}