Search code examples
lualua-tableunpack

Better way to create a single iterative unpack function in lua


Lua unpack funtion works only for simple table, so I though to write a function which can unpack complex tables. It works fine but I am looking for better ways to write such a function. The code is below:

c = {1,2,{3,4},{{5,6},{7,8}}}

vt = {}

function convertToSimpleTable(t,vacantTable)

    if type(t)=="table" then

        for _,val in ipairs(t) do

            if type(val)=="table" then
                convertToSimpleTable(val,vacantTable)
            else
                table.insert(vacantTable,val)
            end
        end
        return vacantTable
    else
        return {t}
    end

end

print(unpack(convertToSimpleTable(c,vt)))

Output:

1   2   3   4   5   6   7   8

For this function to work I need to supply a vacant table because if I initialize a table inside the function it is re initialized as the function is iterative, hence giving wrong results


Solution

  • Just add:

    vacantTable=vacantTable or {}
    

    to the beginning of the function. Or create a second function and call this one from basic wrapper:

    function convertToSimpleTable(t)
      return convertToSimpleTable_impl(t, {})
    end