dotfiles/mzte-nv/src/ffi.zig

42 lines
1.2 KiB
Zig
Raw 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
pub fn luaFunc(comptime func: fn (*c.lua_State) anyerror!c_int) c.lua_CFunction {
return &struct {
fn f(l: ?*c.lua_State) callconv(.C) c_int {
return func(l.?) catch |e| {
var buf: [128]u8 = undefined;
const err_s = std.fmt.bufPrintZ(
&buf,
"Zig Error: {s}",
.{@errorName(e)},
) catch unreachable;
c.lua_pushstring(l, err_s.ptr);
_ = 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];
}