Skip to content

Instantly share code, notes, and snippets.

@SkyyySi
Last active May 20, 2022 18:01
Show Gist options
  • Select an option

  • Save SkyyySi/d211d3e54e52423d86cf41ea1f5467dc to your computer and use it in GitHub Desktop.

Select an option

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).
#!/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
@SkyyySi
Copy link
Author

SkyyySi commented May 20, 2022

Also, here's an alternative version if you prefer to put your arguments in parentheses over pipes:

--- Create a simple anonymous function with a Lua-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("^(%([^%)]*%))(.*)") ---@type string, string
	return load("return function"..args.."return "..body..";end")() ---@type function
end

return lambda

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment