lua-users home
lua-l archive

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


On Monday 16 January 2006 3:59 pm, Henderson, Michael D wrote:
> The PIL says, "With proper iterators, we can traverse almost anything,
> and do it in a readable fashion." I guess that I'm just not
> understanding iterators.
>
> If I have an entry like the following
>
> entry = { timestamp = "2006/01/16 132155"
>         , { "cpu" , 42.3  }
>         , { "fan" , 5823  }
>         , { "aaa" , "bbb" }
>         };
>
.... snip......
>
> Which leads me to another question. Is there a better way to write this?

i like to write coroutine iterators (UNTESTED):

function get_iter (t)
  return coroutine.wrap (function ()
    if not t.timestamp then
      error ("missing timestamp")
    end
    for _, v in ipairs (t) do
      if (type (v) ~= "table" or not (v[1] and v[2])) then
        error ("bad entry")
      end
      coroutine.yield (v[1], v[2])
    end
  end)
end

might be a bit slower than a handcoded state machine, but much easier to read

i wonder why you want the timestamp test in the iterator..., maybe it would be 
better in the iterator factory:

function get_iter (t)
  if not t.timestamp then
    error ("missing timestamp")
  end
  return coroutine.wrap (function ()
    for _, v in ipairs (t) do
      if (type (v) ~= "table" or not (v[1] and v[2])) then
        error ("bad entry")
      end
      coroutine.yield (v[1], v[2])
    end
  end)
end


-- 
Javier

Attachment: pgpiEQsQkmq89.pgp
Description: PGP signature