lambda
lambda
function lambda( def ) --> func, err
Description
Allows to define functions using a compact lambda-like syntax.
This function internally works by expanding the following patterns into a standard lua function definition. Then it is parsed by the common Lua load/loadstring function.
The fundamental expanded pattern is prologue|statement;expression.
It generate a function that has prologue as nominal arguments. It can be a comma separated list, like in x,y,z|statement;expression.
Then the statement will be injected as the function body. It must be a sequence of lua statements like in prologue|for k = 1,10 do print(k) end print("ok");expression.
At end of the function the expression will be returned. So it must be a valid Lua expression like in prologue|statement;math.random(2).
When the prologue is missing, a default one will be used consisting of the first 6 alphabet letters. expression must always be given but the statement and the separation ; can be missing. Indeed, in the main use case, prologue and statement will be missing and only the expression will be given.
Parameters
- def
-
This is the string containing the function definition. The syntax is described in the previous section.
Return Values
- func
-
A new function is returned, behaving accordly the def string or nil if an error occurse.
- err
-
A message if an error occurse otherwise nil.
Code
--ZFUNC-lambda-v0 local function lambda( def ) --> func, err -- Compatibility wrapper local function compat_load( chunk ) local chunkname = "lambda" if _VERSION ~= "Lua 5.1" then return load( chunk, chunkname, "t" ) else return loadstring( chunk, chunkname ) end end -- Find the body and symbolic arguments local symb, body = def:match( "^(.-)|(.*)$" ) if not arg or not body then symb = "a,b,c,d,e,f,..." body = def end -- Split statements from the last expression local stat, expr = body:match( "^(.*;)([^;]*)$" ) -- Generate standard lua function definition local func = "return( function( "..symb..")" if not expr or expr == "" then func = func.."return "..body else func = func..stat.."return "..expr end func = func.." end )( ... )" -- Generate the function return compat_load( func ) end return lambda
Examples
local t = require "taptest" local lambda = require "lambda" -- lambda-like syntax t( 1, lambda"x|x+1"( 0 ) ) -- additional statement, only the last expression is returned t( 3, lambda"x| x=x+1; x+1"( 1 ) ) -- default args are a,b,c,d,e,f,...( vararg ) t( 1, lambda"a+1"( 0 ) ) t()