该表的结构如下:
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/