麻烦操纵Lua表

时间:2015-01-07 03:11:41

标签: loops lua logic lua-table

我们说我有两张桌子:

veggie_multiples = {
{veggie = "carrot", quantity = 1},
{veggie = "tomato", quantity = 2},
{veggie = "celery", quantity = 3}}

veggie_singles = {
{veggie = "celery"},
{veggie = "carrot"},
{veggie = "potato"},
{veggie = "carrot"},
{veggie = "potato"}}

我希望最终得到一张代表:

的表格
veggie_multiples = {
{veggie = "carrot", quantity = 3},
{veggie = "tomato", quantity = 2},
{veggie = "celery", quantity = 4},
{veggie = "potato", quantity = 2}}

我尝试过类似的事情:

veggie_multiples = {
{veggie = "carrot", quantity = 1},
{veggie = "tomato", quantity = 2},
{veggie = "celery", quantity = 3}}

veggie_singles = {
{veggie = "celery"},
{veggie = "carrot"},
{veggie = "potato"},
{veggie = "carrot"},
{veggie = "potato"}}

for i, n in ipairs(veggie_singles) do
    for ii, nn in ipairs(veggie_multiples) do
        if veggie_singles[i].veggie == veggie_multiples[ii].veggie then
            veggie_multiples[ii].quantity = veggie_multiples[ii].quantity + 1
            table.remove(veggie_singles, i)
        else
            table.insert(veggie_multiples, {veggie = veggie_singles[i], quantity = 1})
            table.remove(veggie_singles, i)
        end
    end
end

for i, n in ipairs(veggie_multiples) do
    print(veggie_multiples[i].veggie, " ", veggie_multiples[i].quantity)
end

无论我尝试什么,我都无法工作。请帮忙!谢谢。

2 个答案:

答案 0 :(得分:3)

使用ipairs的for循环遍历索引和值 for i, n in ipairs(veggie_singles)将在第一次迭代中提供i=1 and n={veggie="celery"},依此类推。代码不需要使用i所以在Lua中你使用_作为抛弃。然后搜索素食倍数中与素食单相同的条目。如果找不到则添加它,如果找到则增加数量。

for _, vs in pairs(veggie_singles) do
    local found = false
    for _, vm in pairs(veggie_multiples) do
       if vm.veggie == vs.veggie then
          vm.quantity = vm.quantity + 1
          found = true
          break
       end
    end
    if not found then
        table.insert(veggie_multiples, {veggie=vs.veggie, quantity=1}) 
    end
end


for i, n in ipairs(veggie_multiples) do
    print(veggie_multiples[i].veggie, " ", veggie_multiples[i].quantity)
end

由于索引对问题不是很有用,而且名称是你想要查找的东西,你可以使用名称作为表中的键来简化代码。

quantity = {carrot=1, tomato=2, celery=3}
add = {"celery", "carrot", "potato", "carrot", "potato"}

for _, v in pairs(add) do
   quantity[v] = (quantity[v] or 0) + 1
end

for veggie, qty in pairs(quantity) do
   print(veggie, qty)
end

输出:

potato  2
carrot  3
celery  4
tomato  2

答案 1 :(得分:1)

这有效:

for i, n in ipairs(veggie_singles) do
    local existed = false
    for ii, nn in ipairs(veggie_multiples) do
        if veggie_singles[i].veggie == veggie_multiples[ii].veggie then
            veggie_multiples[ii].quantity = veggie_multiples[ii].quantity + 1
            existed = true
            break
        end
    end
    if not existed then
        table.insert(veggie_multiples, {veggie = veggie_singles[i].veggie, quantity = 1})
    end
end

仅当veggie_singles[i].veggie中的项目不等于veggie_multiples中的所有项目时,才会插入新项目。这是标志existed的作用。