lua-users home
lua-l archive

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


Hello,

I was building a couple of little handy utilities for list-like tables (see code below). (I have a List 'pseudo-type-metatable', aliased as L, mainly to have them show properly on debug output). One of them is 'queue', an iterator on items 2..#l . A surprise came up when testing it; here is the output of a sample case:

=== queue ===
l                : L{"a", "b", "c", "d", "e"}
queue            : function: 0x8d3ee68
items of queue   : (2,"b") (3,"c") (4,"d") (5,"e")
listing(queue)   : L{"b", "c", "d", "e"}

('listing' makes a list out of an iterator's items.)
The point is the traversal, with indices matching the _original_ list, not the queue. I find that very nice --even if we nearly never need indices of a traversal, afaik...
What do you think?
Have you ever seen such a behaviour?
Also, should I let things that way?

Denis

piece of code, case of:

--[[  First item / queue of a list.
      -- Queue is an iterator ! It return (i,item) pairs like ipairs.
]]
List.first = function(l) return l[1] end
List.queue = function (l)
   local i = 1
   return function ()
      if i < #l then
         i = i + 1
         return i, l[i]
      end
      return nil
   end
end

--[[  List-ing of an iterator.
      Builds a new list out of the items traversed by the iterator.
]]
listing = function (iter)
   local l = L{}
   for _,item in iter do l[#l+1] = item end
   return l
end