后挂钩函数,后处理并传递所有返回 [英] Post-hook a function, post-process and pass through all returns

查看:19
本文介绍了后挂钩函数,后处理并传递所有返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个后挂钩函数,它为自己接收一些数据,引用另一个函数和 ... 中该任意函数的参数.在引用的函数返回后,此函数会进行一些后处理.为简单起见,我们只记下时间:

I have a post-hook function that receives some data for itself, reference to another function and arguments for that arbitrary function in .... This function does some post-processing, after referenced function returns. For simplicity let's just note time:

function passthrough(tag, func, ...)
    metric1[tag] = os.time()
    func(...)
    metric2[tag] = os.time()
end

由于需要后处理,所以不能马上return func(...),也不知道会有多少return.完成后处理后,如何通过这些退货?

Since I need to postprocess, I can't immediately return func(...) and I don't know in advance how many returns there will be. How can I passthrough those returns after I'm done with post-processing?

到目前为止,我只能考虑在 local results = { func(...) } 中打包调用,然后使用 return unpack(results) 或制作后处理器使用所有必要数据作为上值生成后处理闭包的工厂:

So far I can think only of packing call in local results = { func(...) } and then using return unpack(results) or making a postprocessor factory that'd generate postprocessing closure with all necessary data as upvalues:

local function generate_postprocessor(tag)
    return function(...)
        metric2[tag] = os.time()
        return ...
    end
end

function passthrough2(tag, func, ...)
    metric1[tag] = os.time()
    return generate_postprocessor(tag)(func(...))
end

但是,考虑到大量迭代和应用程序的实时性,这两种方法都会引入一些不希望出现的开销.有没有更简单的?

However, both those approaches would introduce some overhead that is undesirable, considering high amount of iterations and real-time nature of application. Is there anything simpler?

推荐答案

你不需要闭包.func 在调用闭包生成器之前被调用.您只需要一个将其参数直接传递给其返回值的函数,即可为您的第二个标签提供一个挂钩点:

You don't need the closure. func is called before calling your closure generator anyway. You just need a function that passes its arguments straight through to its return values to give you a hook point for your second tag:

function passthrough_return(tag, ...)
    metric2[tag] = os.time()
    return ...
end

function passthrough(tag, func, ...)
    metric1[tag] = os.time()
    return passthrough_return(tag, func(...))
end

您仍然会获得额外函数调用的开销,但这比创建闭包或表要好,而且远低于前/后处理的开销.

You're still getting the overhead of an extra function call, but that's better than creating a closure or a table and far less than the overhead of your pre/post processing.

这篇关于后挂钩函数,后处理并传递所有返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆