Lua支持装饰器吗?

发布于 2024-09-16 23:22:47 字数 287 浏览 1 评论 0原文

我有 Python 背景,非常喜欢 Python 装饰器的强大功能。

Lua支持装饰器吗?

我已阅读以下链接,但我不清楚: http://lua-users.org/wiki/ DecoratorsAndDocstrings

更新

如果可能的话,您是否介意给出一个如何在 Lua 中实现它的示例。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想挽留 2024-09-23 23:22:47

您引用的页面上记录的“装饰器”(例如在 这个 中用于添加类型-checking)与 Python 的奇怪命名的“装饰器语法”(用于应用高阶函数(HOF)的特定方式)关系不大——相反,Lua wiki 中描述和使用的装饰器是支持应用程序的 Lua 习惯用法装饰器设计模式到 Lua 函数(通过保存“额外属性”——例如文档字符串,类型检查函数等——在单独的全局表中)。

Lua 确实支持 HOF(我不确定您是否可以将函数名称重新绑定到将 HOF 应用于函数的结果,但是您可以轻松地,如 wiki 页面所示,使用匿名“原始函数”,仅将名称绑定到 HOF 的结果,并以该匿名函数作为参数)。

Python 的“装饰器语法”语法糖很好(而且令我惊讶的是,似乎大多数 Python 爱好者对 HOF 的使用增加了一个数量级!-),但是它们没有什么内在或本质的东西是你不能做的在 Lua 中(Lua 的匿名函数无论如何都围绕着 Python 的愚蠢的、有限的 lambda 运行——就像在 Javascript 中一样,它们本质上具有相同的功能,并且几乎相同的语法,作为一个名为“正常”的函数)功能!-)。

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!-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文