如何在我的 Lua 表格中格式化值:t={['foo']=true,['bar']=true}?

这与之前的问题有关:在多个位置检查值并仅在源唯一时返回匹配

本质上,该函数依赖于数据的格式为:

local vendors = {
                 Asda = {Kellogg = true, Cadbury = true, Nestle = true, Johnsons = true, Pampers = true, Simple = true},
                 Tesco = {Kellogg = true, Cadbury = true, Nestle = true, Johnsons = true},
                 Spar ={Nestle = true, Johnsons = true, Pampers = true, Simple = true}
               }

然而,我通过循环遍历路径位置并将它们添加到表中来收集数据,这只会创建如下列表:

Asda = {"Kellogg", "Cadbury", "Nestle", "Johnsons", "Pampers", "Simple"}

我还可以通过以下方式添加它们:

local Asda = {}
for index = 1, 9 do
local pathAsda = factReference -- 某些路径位置,随着索引的增加而变化
if pathAsda ~= "" then
    Asda[#Asda+1] = {[Asda] = true} -- table.insert(Asda, pathAsda), 对于先前提到的格式
end

这会留下以下结果:

 Asda= {{Kellogg = true}, {Cadbury = true}, {Nestle = true}, {Johnsons = true}, {Pampers = true}, {Simple = true}}

然后我会使用:

table.insert(vendorSources,Asda)

这两种格式都不适用于答案中的函数,我似乎无法弄清楚如何修改任何部分以使其正常工作。

function intersection(s1, s2) -- 找出两个集合(s1 & s2)是否重叠
local output = {}

  for key in pairs(s1) do
    output[#output + 1] = s2[key]
  end
return output
end

有一种方法可以编辑列表(Asda)以使其格式正确吗?

点赞
用户1442917
用户1442917

你需要使用 Asda[pathAsda] = true 而不是 Asda[#Asda+1] = {[pathAsda] = true},但是请记住,在这种情况下元素的顺序是不保证的。

2019-09-24 14:00:58