假设我有两个表:
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
无论我尝试什么,我都无法让它发挥作用。请帮忙!谢谢你。
最佳答案
使用 ipairs 的 for 循环迭代索引和值,所以for i, n in ipairs(veggie_singles)
将在第一次迭代中给出 i=1 and n={veggie="celery"}
,依此类推。代码不需要使用 i
,所以在 Lua 中你使用 _ 作为扔掉。然后在 veggie multiples 中搜索与 veggie single 同名的条目。如果未找到则添加它,如果找到则增加数量。
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
关于loops - 操作 Lua 表的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27810883/