Skip to content

Commit 08bf149

Browse files
committed
fix: allow all types with user-defined decls
1 parent 8470eb9 commit 08bf149

File tree

2 files changed

+18
-17
lines changed

2 files changed

+18
-17
lines changed

src/lib.zig

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5422,24 +5422,25 @@ pub fn exportFn(comptime name: []const u8, comptime func: anytype) CFn {
54225422
///
54235423
/// };
54245424
///
5425-
/// const funcs = fnRegsFromStruct(MyLib);
5425+
/// const funcs = fnRegsFromType(MyLib);
54265426
/// lua.newLib(funcs);
54275427
/// lua.setGlobal("mylib"); // mylib.foo, mylib.bar now visible
54285428
/// ```
5429-
pub inline fn fnRegsFromStruct(comptime T: type) []const FnReg {
5430-
comptime {
5431-
const decls = switch (@typeInfo(T)) {
5432-
.@"struct" => |info| info.decls,
5433-
else => @compileError("Expected struct, found '" ++ @typeName(T) ++ "'"),
5434-
};
5435-
var funcs: [decls.len]FnReg = undefined;
5436-
for (decls, 0..) |d, i| {
5437-
funcs[i] = .{
5429+
pub fn fnRegsFromType(comptime T: type) []const FnReg {
5430+
const decls = switch (@typeInfo(T)) {
5431+
inline .@"struct", .@"enum", .@"union", .@"opaque" => |info| info.decls,
5432+
else => @compileError("Type " ++ @typeName(T) ++ "does not allow declarations"),
5433+
};
5434+
comptime var funcs: []const FnReg = &.{};
5435+
inline for (decls) |d| {
5436+
if (@typeInfo(@TypeOf(@field(T, d.name))) == .@"fn") {
5437+
const reg: []const FnReg = &.{.{
54385438
.name = d.name,
5439-
.func = wrap(@field(T, d.name)),
5440-
};
5439+
.func = comptime wrap(@field(T, d.name)),
5440+
}};
5441+
funcs = funcs ++ reg;
54415442
}
5442-
const final = funcs;
5443-
return &final;
54445443
}
5444+
const final = funcs;
5445+
return final;
54455446
}

src/tests.zig

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3094,7 +3094,7 @@ test "checkNumeric and toNumeric" {
30943094
}
30953095
}
30963096

3097-
test "function registration with fnRegsFromStruct" {
3097+
test "function registration with fnRegsFromType" {
30983098
const lua: *Lua = try .init(testing.allocator);
30993099
defer lua.deinit();
31003100

@@ -3115,12 +3115,12 @@ test "function registration with fnRegsFromStruct" {
31153115
// Construct function registration table at comptime from
31163116
// public decls on MyLib.
31173117

3118-
const funcs = zlua.fnRegsFromStruct(MyLib);
31193118
if (zlua.lang == .lua51 or zlua.lang == .luau or zlua.lang == .luajit) {
3119+
const funcs = comptime zlua.fnRegsFromType(MyLib);
31203120
lua.newTable();
31213121
lua.registerFns("fnregs", funcs);
31223122
} else {
3123-
lua.newLib(zlua.fnRegsFromStruct(MyLib));
3123+
lua.newLib(comptime zlua.fnRegsFromType(MyLib));
31243124
lua.setGlobal("fnregs");
31253125
}
31263126
try lua.doString("res = fnregs.add(100, fnregs.neg(25))");

0 commit comments

Comments
 (0)