Lua笔记(14)—— generic for

Generic for的语法:

for <var-list> in <exp-list> do
    <body>
end

通常情况,<exp-list>只包含一个元素:a call to an iterator factory。而<var-list>大多数也只含有一个变量,第一个变量称之为“控制变量”,当它变为nil时,循环退出。

Generic for首先计算in后的表达式,<exp-list>最终生成3个值:iterator functioninvariant stateinitial value for the control variable。同multiple assignment一样,只有最后一个(或唯一一个)表达式可以生成多个值。

初始化以后,generic for调用iterator function,传入invariant stateinitial value for the control variable作为参数。从generic for出发点来看,invariant state没什么意义,generic for只在初始化时候,才把invariant state传入iterator function。(请参考:How to understand “invariant state” in generic for?

实际上:

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

举个例子,iterator functionfinvariant statesinitial value for the control variablea0。则control variable的值则会依次为:a1 = f(s, a0)a2 = f(s, a1),直到为nil。

发表评论

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

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