为什么Lua的迭代器是三元组?

发布于 2024-11-03 00:41:05 字数 484 浏览 4 评论 0原文

Lua 5.1 的参考手册指出,迭代器

 for var_1, ···, var_n in explist do block end

相当于以下代码:

 do
   local f, s, var = explist
   while true do
     local var_1, ···, var_n = f(s, var)
     var = var_1
     if var == nil then break end
     block
   end
 end

Why does Lua require the 'state' variable,s?

我猜这意味着迭代器函数不需要携带任何迭代器状态(例如,参见 ipairs 迭代器生成函数的设计),但是创建起来非常简单带有这种状态的按需闭包,并且每次迭代的成本几乎是一次,基于效率的情况对我来说并不是那么清楚。

Lua 5.1's reference manual states that an iterator

 for var_1, ···, var_n in explist do block end

is equivalent to the code:

 do
   local f, s, var = explist
   while true do
     local var_1, ···, var_n = f(s, var)
     var = var_1
     if var == nil then break end
     block
   end
 end

Why does Lua require the 'state' variable, s?

I would guess that it means that the iterator function does not need to carry any per-iterator state (see, e.g., the design of the ipairs iterator-yielding function), however it is quite straightforward to create closures on demand that carry this state, and the cost is pretty much once per iteration, the efficiency-based case is not that clear to me.

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

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

发布评论

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

评论(2

风蛊 2024-11-10 00:41:05

因为三重设计不会阻止您使用闭包,而替代方法会阻止您使用闭包。有时外部状态设计是更简单的方法。

例如,假设您正在使用 for 循环来迭代在对 RESTful 查询的响应中显示哪些页面。通过基于外部状态的循环,您可以编写一个函数,该函数基于表示查询的状态表示参数的表来迭代页面(您可以从 URL 构造一次该表,然后将其重用于多个其他函数)。使用三元组,您可以仅使用这些值进行迭代,而不必将其(以及所有其他类似的函数)包装在闭包构造函数中。

Because the triple design doesn't prevent you from using a closure, while the alternative approach prevents you from not using closures. Sometimes the external-state design is the simpler approach.

For instance, say that you're using a for loop to iterate which pages to display in the response to a RESTful query. With external-state-based loops, you can write a function that iterates pages based on a table representing the state-representational parameters of the query (which you construct from the URL once and reuse for several other functions). With triples, you can iterate with just those values without being forced to wrap it (and every other function like it) in a closure constructor.

如日中天 2024-11-10 00:41:05

为什么不呢?用其他方式来做有什么好处呢?正如微软所说,每一个改变的想法都始于负 100 分

Why not? What's good about doing it some other way? As they say at Microsoft, every idea to change something starts out with minus 100 points.

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