[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Modifying a table during an ipairs loop
- From: Dirk Laurie <dirk.laurie@...>
- Date: Thu, 3 Sep 2015 12:30:45 +0200
The manual says:
The behavior of `next` is undefined if, during the traversal, you
assign any value to a non-existent field in the table. You may however
modify existing fields. In particular, you may clear existing fields.
Under 'pairs' it says:
See function `next` for the caveats of modifying the table during its traversal.
It does not say anything of the kind under `ipairs`, which does not depend
on `next`. The behaviour of operations like t[k]=nil, t[#t+1]=v,
table.insert(t,k,v), table.remove(t,k) is not undefined, but may require
some thought.
What does the following code do?
for k,v in ipairs(t) do if type(v)=='table' then
if v[1] then
table.insert(t,k,v[1]); table.remove(v,1)
else table.remove(t,k)
end
end
Hint: it almost does what it should, but there is a bug.