Skip to content

Instantly share code, notes, and snippets.

@gsuuon
Last active December 12, 2023 18:15
Show Gist options
  • Save gsuuon/b5fb0dfbff4e4a361c1126502548120f to your computer and use it in GitHub Desktop.
Save gsuuon/b5fb0dfbff4e4a361c1126502548120f to your computer and use it in GitHub Desktop.
Pipes in lua with metamethods
local function pipe(val)
return setmetatable({ val = val }, {
__index = function(_, fn)
return pipe(fn(val))
end,
__unm = function(x)
return x.val
end
})
end
print(
- pipe(1)
[ function(x) return x + 1 end ]
[ function(x) return x + 2 end ]
) -- 4
-- Pipes in lua
local function pipe(val)
return setmetatable({ val = val }, {
__add = function(x, fn)
return pipe(fn(x.val))
end,
__unm = function(x)
return x.val
end
})
end
-- Use as wrapped value
local v =
pipe(1)
+ function(x) return x + 1 end
+ function(x) return x + 2 end
print(-v) -- 4
-- or paren with unwrap
print(
- (pipe('a')
+ function (x) return x .. 'b' end
+ function (x) return x .. 'c' end
)
) -- abc
-- no lsp support
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment