lua - 操作表键

标签 lua data-manipulation lua-table

该表的结构如下:

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

第一步是将“track”键替换为“aura”键。为此我创建了这个函数

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

运行probe(t)命令,表格变为

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

第二步包括创建与字符串“one#two#third”中的标记一样多的 { ["aura"] = word } 形式的表。为此,我创建了该函数

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

我得到的决赛 table 是这个

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

但是“四”值消失了

最佳答案

因为您从 1 开始插入元素。要将元素插入到空槽中,您可以使用 t[#t+1]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

关于lua - 操作表键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77301309/

相关文章:

Lua 打印在同一行

nginx - 在 Nginx 上使用 Lua 重定向到相同的 URL(openresty 设置)

r - 比较如果条件满足,则重置序列的有效方法( R )

r - 在 dplyr 中创建新索引/重新索引

lua - 如何在初始化期间自引用表

c++ - 推送 Lua 表

r - 对 r 中具有特定条件的行求和

lua - 在删除 key 时,如何安全地迭代lua表

lua - 在lua脚本中按降序获取 key 列表

.net - 播放 Wav 太快会搞砸