我正在计算我的表中有多少重复项,因此如果我的表中包含:
funnyTable = { bread, bike, laptop, bread, lightbulb, bike, bread }
我需要显示为
sortedTable = { bread = 3, bike = 2, laptop = 1, lightbulb = 1 }
有人对此有解决方案吗?
这可能与另一个表:
local funnyTable = { 1, 2, 3, 3 }
local occurrences = {}
for _,v in pairs(funnyTable) do
if not occurrences[v] then
-- This is a new element, insert a count of 0.
occurrences[v] = 0
end
occurrences[v] = occurrences[v] + 1
end
这将按预期输出{ [1] = 1, [2] = 1, [3] = 2 }
。