2

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);

2 Answers 2

1

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})
Sign up to request clarification or add additional context in comments.

3 Comments

You can use varags: function handler(func, ...), local ret = func(...), handler(fun1, "foo",2).
yeah, that'll work too. i don't have any experience with the ellipse notation since we use a 5.0 engine in the project i work on.
yeah, i also realized that passing arguments as a table is better. thanks
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.