#How to write a callback generator

1 messages · Page 1 of 1 (latest)

zenith thorn
#

Hello, I'm trying to have a functions that conforms to a type, and return it from a createHook function. I'm struggling with the syntax,though. I realize that zig doesn't have lambdas - I'm just confused as to how this is supposed to be written:

// return function type here
const HookCommand = fn (sec: *reaper.KbdSectionInfo, command: c_int, val: c_int, val2hw: c_int, relmode: c_int, hwnd: reaper.HWND) callconv(.C) c_char;

// callback creator: the callback is supposed to access the parent's `controller` param.
fn createHook(allocator: Allocator, controller: Controller.Controller) !HookCommand {
    const hook = allocator.create(HookCommand);

// How am I supposed to write this?
const my_hook: HookCommand = fn (sec: *reaper.KbdSectionInfo, command: c_int, val: c_int, val2hw: c_int, relmode: c_int, hwnd: reaper.HWND) c_char {
    _ = .{ sec, val, val2hw, relmode, hwnd };
    if (controller.action_ids == null) {
        return 0;
    }
    for (controller.action_ids, 0..)|action_id, idx|{
        if (action_id == command){
            // call corresponding button action
            return 1;
        }
    }
};
    hook.* = my_hook;
    return hook;
}
warm pier
#

Not only does Zig not have lambdas, it also does not have closures. What you're doing will result in a 'controller' not accessible from inner function error

zenith thorn
#

oh great.

#

So, is the only way for me to access my controller param from my function through the global scope?

#

The callback I'm trying to create has to be passed to my host application - that's a rigid cpp interface, so I can't change it.

warm pier
#

If you have no way to pass it via the function arguments then I guess it will have to be done through global state

zenith thorn
#

ok, fair enough.