luadata-manipulationlua-table

Manipulating table key


This table is structured like this:

local t = {
        ["track"] = "one#two#three",
        {
            ["track"] = "four"
        }, -- [1]
}

The first step is to replace the "track" key with the "aura" key. For this purpose I created this function

local function probe(tbl)
    for k, v in pairs(tbl) do
        if type(v) == "table" then
            probe(v)
        elseif type(v) == "string" and k == "track" then
            tbl["aura"] = tbl[k]
            tbl[k] = nil
        end
    end
end

running the probe(t) command the table becomes

{
      ["aura"] = "one#two#three",
      {
          ["aura"] = "four",
      }, -- [1]
}

The second step consists in creating as many tables of the form { ["aura"] = word } as there are tokens in the string "one#two#three". For this purpose I created the function

local function updateDB(tbl, depth)
    if depth > 0 then    
        local d = depth    
        for k, v in pairs(tbl) do
            if type(v) ~= 'table' then                
                if k == 'aura' then
                    local count = 1
                    for word in v:gmatch(("[^%s]+"):format("#")) do
                        tbl[count] = { ["aura"] = word }
                        count = count + 1
                    end
                    tbl[k] = nil    
                end
            else 
                d = d - 1
                updateDB(v, d)
            end
        end
    end
end

The final table I get is this

{
      {
          aura= "one",
      }, -- [1]
      {
          aura= "two",
      }, -- [2]
      {
          aura= "three",
      }, -- [3]
}

But "four" value is gone away


Solution

  • Because you started inserting elements from 1. To insert elements into empty slots, you can use either t[#t+1] or table.insert.

    --local count = 1
    for word in v:gmatch(("[^%s]+"):format("#")) do
        tbl[#tbl+1] = { ["aura"] = word }
        --count = count + 1
    end
    
    --local count = 1
    for word in v:gmatch(("[^%s]+"):format("#")) do
        table.insert(tbl, { ["aura"] = word })
        --count = count + 1
    end