【问题标题】:What does closure function mean for Lua?闭包函数对 Lua 意味着什么?
【发布时间】:2020-09-23 15:34:04
【问题描述】:

根据指南(https://www.tutorialspoint.com/lua/lua_quick_guide.htm), 上面写着:

array = {"Lua", "Tutorial"}

function elementIterator (collection)

   local index = 0
   local count = #collection
    
   -- The closure function is returned
    
   return function ()
      index = index + 1
        
      if index <= count
      then
         -- return the current element of the iterator
         return collection[index]
      end
        
   end
    
end

for element in elementIterator(array)
do
   print(element)
end

闭包函数对 Lua 意味着什么?

【问题讨论】:

  • 这能回答你的问题吗? What is a 'Closure'?
  • 闭包是一个使用其父函数的局部变量的函数。例如,您的示例中返回的函数取决于变量indexcountcollection

标签: lua


【解决方案1】:

在 Lua 中,任何函数都是闭包。从狭义上讲,闭包是一个匿名函数,就像您的示例中的返回函数一样。

闭包是一流的:它们可以分配给变量,传递给函数并从它们返回。它们可以是 Lua tables 中的键和值。

与 PHP 或 C++ 不同,闭包可以访问本地范围内的所有变量 -upvalues(在您的示例中,indexcount,它们保持迭代器状态,还有 collection ) 无需显式声明上值。当代码执行离开设置它们的块时,上值仍然存在。

你不能编写没有闭包(或子例程)的迭代器。在您的示例(一个简单的迭代器)中,elementIterator 是一个函数,它接收一个表并返回另一个函数,一个闭包。这个返回的闭包被 generic for 指令一次又一次地调用,直到它返回nil

您可能会觉得这篇论文很有趣:https://www.lua.org/doc/jucs17.pdf

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 2010-09-14
    • 1970-01-01
    • 2013-01-11
    • 2013-09-15
    • 2011-12-28
    • 2020-10-12
    • 2011-06-11
    相关资源
    最近更新 更多