这篇是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
函数上。