Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Lua support Decorators?

I come from a Python background and really like the power of Python Decorators.

Does Lua support Decorators?

I've read the following link but it's unclear to me: http://lua-users.org/wiki/DecoratorsAndDocstrings

UPDATE

Would you also mind given an example how how to implement it in Lua if it's possible.

like image 853
nickb Avatar asked Sep 04 '10 01:09

nickb


1 Answers

The "decorators" documented at the page you quote (and used for example in this one to add type-checking) have little to do with Python's oddly-named "decorator syntax" for a specific way to apply a higher-order function (HOF) -- rather, the decorators described and used in Lua's wiki are a Lua idiom to support an application of the Decorator Design Pattern to Lua functions (by holding "extra attributes" -- such as docstrings, typechecking functions, etc -- in separate global tables).

Lua does support HOFs (I'm not sure if you can re-bind a function name to the result of applying a HOF to the function, but you can easily, as the wiki pages show, use an anonymous "original function" and only bind a name to the HOF's result with that anon function as the arg).

Python's "decorator syntax" syntax sugar is nice (and, to my surprise, seems to have increased the use of HOFs by most Pythonistas by an order of magnitude!-), but there's nothing intrinsic or essential about them that you can't do in Lua (and Lua's anonymous functions run circle around Python's goofy, limited lambda anyway -- just like in Javascript, they have essentially the same power, and pretty much the same syntax, as a "normal" named function!-).

like image 194
Alex Martelli Avatar answered Sep 26 '22 00:09

Alex Martelli