[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Modifying a table during an ipairs loop
- From: Dirk Laurie <dirk.laurie@...>
- Date: Fri, 4 Sep 2015 11:28:23 +0200
2015-09-04 3:02 GMT+02:00 John Smith <0x42484156@gmail.com>:
> Hello Dirk,
>
> Thursday, September 3, 2015, 1:30:45 PM, you wrote:
>
>> 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.
>
> It skips an item in <t> after the previous item was a table and was emptied out.
> Right? Because it should.
What I thought I wrote was something that would "flatten" a table, i.e.
just string out the elements into a list, and the bug is that it can flatten
only tables in which subtables have at least one element in between.
The correct version, which also flattens nested tables, is:
for k,v in ipairs(t) do
while type(v)=='table' do
table.remove(t,k)
for j=#v,1,-1 do table.insert(t,k,v[j]) end
v = t[k]
end
end