lua-users home
lua-l archive

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


On 16 June 2012 12:58, jseb <gmane2010@finiderire.com> wrote:
> Hello,
>
> I try to print elements of this table:
>
> local big =
>  { foo = { "sub1_foo","sub2_foo"  },
>    bar = { "sub1_bar", "sub2_bar" }
>  }
>
> I'd like to get elements in this format:
> "foo","sub1_foo"
> "foo","sub2_foo"
> "bar","sub1_bar"
> "bar","sub2_bar"
>
> So, i've thought it was a nice day to write a closure.
>
> But the closure always returns the same thing ("bar" with it first element).

Generators are a perfect example where yielding coroutines can be
used. What you do is you start an iteration every time you call fx().
Instead, you should make a coroutine out of fx() and use
coroutine.yield() instead of return. This example does what you want:

local big =
 { foo = { "sub1_foo","sub2_foo"  },
   bar = { "sub1_bar", "sub2_bar" }
 }

function iter (t)
    return function()
       for k,v in pairs(t) do
          for sk,sv in  pairs(v) do
             print (k .. " -> " .. sv)
             coroutine.yield(k,sv) -- notice this instead of return
          end
       end
    end
end

fx=coroutine.wrap(iter(big)) -- every time you call fx(), it will
resume the iterator coroutine
fx() -- «bar -> sub1_bar»
fx() -- «bar -> sub2_bar»
fx() -- «foo -> sub1_foo»
fx() -- «foo -> sub2_foo»