该表的结构如下:
local t = {
["track"] = "one#two#three",
{
["track"] = "four"
},
}
第一步是将“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)
命令
{
[1] = {
aura= "four",
},
aura= "one#two#three",
}
第二步包括创建与字符串“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
我得到的决赛桌是这个
{
[1] = {
aura= "one",
},
[2] = {
aura= "two",
},
[3] = {
aura= "three",
},
}
但是“四”值消失了
因为您从 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