Last active
December 12, 2023 18:15
-
-
Save gsuuon/b5fb0dfbff4e4a361c1126502548120f to your computer and use it in GitHub Desktop.
Pipes in lua with metamethods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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