Skip to content

Instantly share code, notes, and snippets.

@starius
Created June 16, 2015 14:36
Show Gist options
  • Save starius/d72f5b2ddc5fd4bf2460 to your computer and use it in GitHub Desktop.
Save starius/d72f5b2ddc5fd4bf2460 to your computer and use it in GitHub Desktop.
filter.lua - pipe of applications of Lua methods
-- Usage:
-- filter = require 'filter'
-- command = filter.lower.trim:split(' ')
-- command(input) --> input:lower():trim():split(' ')
-- command(input2) --> input2:lower():trim():split(' ')
local unpack = unpack or table.unpack
local function makeFilter(func, parent_f, parent, method_name)
return setmetatable({}, {
__index = function(self, key)
-- method without arguments
return makeFilter(function(...)
local v = func(...)
return v[key](v)
end, func, self, key)
end,
__call = function(_, self, ...)
if self == parent then
-- method with arguments
local args = {...}
return makeFilter(function(...)
local v = parent_f(...)
return v[method_name](v, unpack(args))
end)
else
-- application
return func(self, ...)
end
end,
})
end
return makeFilter(function(...)
return ...
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment