nil
nil

Reputation: 295

lua function as argument in C

I'm going to pass a function to another function which should operate with the passed function. For example:

     handler(fun1("foo",2))
     handler(fun2(1e-10))

The handler is something like calling the passed function many times. I'm going to bind handler, fun1, fun2 to C-functions. fun1 and fun2 are going to return some user data with a pointer to some cpp-class so that I can further recover which function was it.

The problem now is that fun1 and fun2 are going to be called before passed to handler. But I don't need this, what I need is the kind of function and its parameters. However, I should be able to call fun1 and fun2 alone without handler:

     fun1("bar",3)
     fun2(1e-5)

Is it possible to get the context the function is called from?

While typing the question, I realized I could do following

    handler(fun1, "foo",2);
    handler(fun2, 1e-10);

Upvotes: 2

Views: 562

Answers (2)

Mud
Mud

Reputation: 29021

You can just bind the call to it's arguments in another function and pass that to your handler function:

function handler(func)
        -- call func, or store it for later, or whatever
end

handler(function() fun1("foo", 2) end)
handler(function() fun2(1e-10) end)

Now handler doesn't have to worry about storing and unpacking an argument table, it just calls a function.

Upvotes: 1

Mike Corcoran
Mike Corcoran

Reputation: 14564

probably the best way is to pass the function in, with the arguments you want called in a table.

function handler(func, args)
    -- do housekeeping here?
    ...
    -- call the function
    local ret = func(table.unpack(args))
    -- do something with the return value?
end

handler(fun1, {"foo", 2})
handler(fun2, {1e-10})

Upvotes: 1

Related Questions