Suppose I have a list that looks like this:
{{'text'}, {'something', 'string'}, {'thing'}}
I want to turn this into the following list:
{'text', 'something', 'string', 'thing'}
"flattening" the nested lists.
This operation is called flattening. It turns "nested" lists like {{'text'}, {'something', 'string'}, {'thing'}} into a "flat" list {'text', 'something', 'string', 'thing'}. A deep flattening can straightforwardly be written as follows:
function flatten(v)
local res = {}
local function flatten(v)
if type(v) ~= "table" then
table.insert(res, v)
return
end
for _, v in ipairs(v) do
flatten(v)
end
end
flatten(v)
return res
end
Usage:
print(table.unpack(flatten{{'text'}, {'something', 'string'}, {'thing'}})) -- text something string thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With