Last active
May 20, 2022 18:01
-
-
Save SkyyySi/d211d3e54e52423d86cf41ea1f5467dc to your computer and use it in GitHub Desktop.
A simple lambda expression parser for Lua. Doesn't support accessing local variables (besides the parameters).
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
| #!/usr/bin/env lua | |
| --- Create a simple anonymous function with a Ruby-like syntax. | |
| --- | |
| --- Usage: | |
| --- | |
| --- ``` | |
| --- local lambda = require("lambda") | |
| --- f = lambda[[|x, y| x + y + 2]] | |
| --- print(f(3, 6)) | |
| --- --stdout> 11 | |
| --- ``` | |
| ---@param expr string The lambda expression to evaluate | |
| ---@return function The created function | |
| local function lambda(expr) | |
| local args, body = expr:match([[^%s*|%s*(.*)%s*|%s*(.*)%s*]]) ---@type string, string | |
| return load("return function("..args..") return "..body.."; end")() ---@type function | |
| end | |
| return lambda |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, here's an alternative version if you prefer to put your arguments in parentheses over pipes: