Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested lists in Lua

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.

like image 378
kornelbut Avatar asked Jun 13 '26 18:06

kornelbut


1 Answers

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 
like image 146
LMD Avatar answered Jun 16 '26 14:06

LMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!