== Concise Anonymous Functions == *'''Backwards compatible:''' yes *'''Lines changed/added/deleted:''' 3/26/0 *'''Lua authors' position:''' ? *'''Author:''' Brian Palmer (luausers [at] brian codekitchen (dot) net) *'''Last update:''' 2007-Jun-10 * [http://svn.codekitchen.net/lua_patches/lambda.patch] (Patched against Lua 5.1.2) Some syntactic sugar for writing more concise anonymous functions, very useful when passing arguments to higher-order functions. Completely backwards compatible and only modifies the parser, emits the same bytecode as the old syntax. As an example, the old syntax (assuming you've defined a 'filter' method, standard in functional programming style): open_exits = location.exits:filter(function (e) return not e:is_locked() end) With new syntax: open_exits = location.exits:filter( [(e) | not e:is_locked()] ) The patch makes three changes: - Most importantly, anonymous functions can be defined between square [] brackets, taking advantage of the fact that there is no ambiguity between when you are indexing a table and when you are defining a function. The argument list can be left off, in which case the function is implied vararg: function pass_through(f) return function(...) do_something_useful(...); return f(...) end end becomes: function pass_through(f) return [ do_something_useful(...); | f(...) ] end - The pipe | character is short-hand for the 'return' keyword. If you'd prefer not to have this behavior, maybe because you've installed a bitwise operator patch, simply remove the one line from the patch that defines the operator. - Lastly, 'then' becomes optional in 'if' constructs. In the current version of Lua, 'if' statements can be parsed just as well without a 'then' keyword, however if you take advantage of this keep in mind that the Lua authors may change this is the future (of course this applies to any power patch). Quick example: if a > 5 then return 'hi' else return 'bye' end now can be written: if a > 5 | 'hi' else | 'bye' end or: if a > 5 return 'hi' else return 'bye' end Of course, the | and 'then' keyword additions are available to all lua code, not just code inside [] functions. | looks kind of weird at first, but it's grown on me quickly. Here's an example from a recent project: function describe_floor(location, objs, obj_locs) | objs :iselect(curry(is_at, location, obj_locs)) :map([ (o) | "you see a "..o.." on the floor." ]) :concat' ' end