I am trying to call a method based on runtime values. Consider this method:
fn add(a: i32, b: i32) i32 {
return a + b;
}
And this runtime known array:
const args = // a runtime value that contains .{ "add", "1", "2" };
I want to call add with 1 and 2 as parameter. I know how to define a set of function like this:
const named_functions = .{
.{ .name = "add", .func = add },
.{ .name = "foo", .func = foo },
// ...
};
And then a method makeCall would go though the tuple, select the function based on the name, convert the arguments depending on the @typeInfo(FuncType).@"fn".params and use @call. But @call expects a tuple to make the call:
@call(.auto, "add", .{ 1, 2 });
And this is where I get a little stuck. How to go from a dynamically known array to a tuple?
I could switch on the number of argument (pseudo code):
switch (@typeInfo(FuncType).@"fn".params.len) {
1 => @call(auto, name, .{ convert(paramType, args[1]) }),
2 => @call(auto, name, .{ convert(paramType, args[1]), convert(paramType, args[2])}),
...
}
But isn’t there a way to create a tuple at compile time with the content of an array? Something like (pseudo-code):
const max_nb_args = getMaxNbArgs(named_functions);
inline for (max_nb_args) |nb_arg| {
if (nb_arg == @typeInfo(FuncType).@"fn".params.len) {
const params = convertArgs(@typeInfo(FuncType).@"fn".params, args);
@call(auto, name, .{ ...param1 }), // magic
}
}
Is there a zig construct to do that?