lua-users home
lua-l archive

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


On Wed, May 26, 2010 at 3:15 PM, steve donovan
<steve.j.donovan@gmail.com> wrote:
> On Wed, May 26, 2010 at 4:03 PM, Eike Decker <zet23t@googlemail.com> wrote:
>> I might be wrong, but I think this is actually buggy. Usually, you
>> would do it that way:
>
> Ah, but it does actually work (one of my new year's resolutions was
> never to post untested code ;))
>
> According to the manual, one may delete keys in a next() traversal.
> (Adding them is not guaranteed to work)
>
> steve d.
>

But next() is irrelevant to ipairs(). The point is that, in an
ipairs() loop, if you use table.remove() to remove an element from the
table at the current (or previous) index, the next loop iteration will
appear to have "skipped over" an element. For example:

 -- nine empty strings
 local blanks = {'','','','','','','','',''}

 for i,v in ipairs(blanks) do
   if (v == '') then
     table.remove(blanks,i)
   end
 end

 for i,v in ipairs(blanks) do
   print(string.format('%d: %q', i, v))
 end

 -- output:
 -- 1: ""
 -- 2: ""
 -- 3: ""
 -- 4: ""


-Duncan