如何将 lua table 中的值格式化为:t = {['foo'] = true, ['bar'] = true}?

How do I format values in my lua table to be: 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}
               }

但是,我通过循环遍历路径位置并将它们添加到 table 中来收集数据,这只会创建一个列表,例如:

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

我可以通过另一种方式添加它们:

local Asda = {}
for index = 1, 9 do 
local pathAsda = factReference -- some path location which changes by index increasing
if pathAsda ~= "" then
    Asda[#Asda+1] = {[Asda] = true} -- table.insert(Asda, pathAsda), for the previously mentioned format
end

这会给我留下:

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

然后我会使用:

table.insert(vendorSources,Asda)

这些格式都不能与答案中的函数一起使用,我似乎无法弄清楚如何修改任何部分以使其起作用。

function intersection(s1, s2) -- finds out if two sets (s1 & s2) overlap
local output = {}

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

有没有办法将任一列表 (Asda) 编辑为正确的格式?

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