Zig NEWS

Discussion on: How to make a function lookup table (LUT)

Collapse
 
pjz profile image
Paul Jimenez

zig doesn't support directly indexing functions

I'm not sure what you mean, but the following works fine for me in 0.8.0:

fn hiFun1() void {                                                             
    std.debug.print("hi\n", .{});                                              
}                                                                              

fn hiFun2() void {                                                             
    std.debug.print("hello\n", .{});                                           
}                                                                              

const FnType = fn () void;                                                     
const hiFuns = [_]FnType{ hiFun1, hiFun2 };                                    

pub fn main() void {                                                           
    var i: usize = 1; // or maybe have it be a user input.                     
    hiFuns[i](); // prints out "hello"                                        
}
Enter fullscreen mode Exit fullscreen mode

Your code is a bit different in that your lookupTable function both generates the functions for the lookup table and assembles them into the lookup table. If they need to be generated, that's fine, but if they're static, the above method will work with less complication.

Collapse
 
ityonemo profile image
Isaac Yonemoto • Edited

This is for situations where you don't know the functions ahead of time: perhaps they need to be generated based on the index, perhaps the length of the array depends on the size of a datatype, e.g.

Yeah, perhaps that is not best described as "directly indexing".