Lua笔记(15)—— “Lua Closures and Iterators”读书笔记

这篇是Lua Closures and Iterators的读书笔记:

(1)Closure有以下属性:

a) A function inside a function;
b) The inner function can see local variables of the outer function.

利用closure可以实现下列feature

a) Iterators;
b) OOP class like devices.

(2)Iterators and For Loops

代码示例:

#!/usr/bin/lua

function positive_integers(max)
    local n = 0
    return function()
        n = n + 1
        if n > max then
            return nil
        else
            return n
        end
    end
end

for v in positive_integers(3) do
    print(v)
end

Iterator含义如下:

An iterator is a function inside a function where the inner function sees the outer function's local variables. The inner function does something to increment or cycle through the local variable(s) in the outer function, returning the new value of the outer function's local variable, or something depending on that new value. The outer function passes the inner function back as a function return.

在上面例子中,iterator就是positive_integers()返回的匿名函数。

Generic for既不作用在iterator函数的返回值上,也不作用在iterator make函数上(positive_integers),而是作用在iterator函数上。

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.