lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi Daurnimator,

"In this case I passed 'self' as the state parameter; which neatly
lines up with the 'self' parameter required to the `next_foo` call."

which neatly lines up with the 'last' parameter?

Best Regards
Nan Xiao

On Tue, Aug 18, 2015 at 11:24 AM, Daurnimator <quae@daurnimator.com> wrote:
On 18 August 2015 at 13:06, Nan Xiao <xiaonan830818@gmail.com> wrote:
> Hi all,
>
> In ''7.2 The Semantics of the Generic for" section of Pil 3, it refers:
>
>  (From the standpoint of the for construct, the invariant state has no
> meaning at all.
> The for only passes the state value from the initialization step to the
> calls to the iterator
> function.)
>
> But in following part:
>    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
> I can see the "invariant state" is used in every iterator function call. So
> does it mean although the
> "invariant state" is passed in every iterator function call, but actually
> iterator function doesn't use it
> except the first time?


The "invariant state" in the code you posted is _s
The function _f is user provided; and it may use the 'state' argument
_s as much as it wants.
In actual code, this may look like:

function someobject:next_foo(last)
    return next(self.sub_data, last)
end

function someobject:each_foo()
    return self.next_foo, self
end

In this case I passed 'self' as the state parameter; which neatly
lines up with the 'self' parameter required to the `next_foo` call.
Without the state parameter, you'd be forced to create a closure for each call:

function someobject:each_foo()
    return function(last) return self:next_foo(last) end
end