Lua 函数链功能

本文介绍Lua中函数链的概念及其实现方式,展示了如何通过组合多个函数来创建复杂操作,并探讨了过滤器、源和接收器在网络数据流中的作用。

函数链

http://lua-users.org/wiki/FiltersSourcesAndSinks

A chain is a function that combines the effect of two (or more) other functions, but whose interface is indistinguishable from the interface of one of its components. Thus, a chained filter can be used wherever an atomic filter can be used. However, its effect on data is the combined effect of its component filters. Note that, as a consequence, chains can be chained themselves to create arbitrarily complex operations that can be used just like atomic operations.

 

DEMO

local function chain2(f1, f2)
  return function(chunk)
    local ret = f2(f1(chunk))
    if chunk then return ret
    else return ret .. f2() end
  end
end

local filter = {}
function filter.chain(...)
  local f = arg[1]
  for i = 2, table.getn(arg) do
    f = chain2(f, arg[i])
  end
  return f
end


local function addOne( subject )
    return subject + 1
end

local function minOne( subject )
    return subject - 1
end

local nullFunc = filter.chain(addOne, minOne)

local result = nullFunc(56)
print(result)


local nullFunc_1 = filter.chain(minOne, addOne)
local result = nullFunc_1(6)
print(result)

 

扩展

Filters can be seen as internal nodes in a network through which data flows, potentially being transformed along its way. Chains connect these nodes together. To complete the picture, we need sources and sinks as initial and final nodes of the network, respectively. Less abstractly, a source is a function that produces new data every time it is called. On the other hand, sinks are functions that give a final destination to the data they receive. Naturally, sources and sinks can be chained with filters.

Finally, filters, chains, sources, and sinks are all passive entities: they need to be repeatedly called in order for something to happen. Pumps provide the driving force that pushes data through the network, from a source to a sink.

http://lua-users.org/wiki/FiltersSourcesAndSinks

 

转载于:https://www.cnblogs.com/lightsong/p/6351350.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值