LUA表中条目的数量

问题描述 投票:-2回答:1

我正在计算我的表中有多少重复项,因此如果我的表中包含:

funnyTable = { bread, bike, laptop, bread, lightbulb, bike, bread } 

我需要显示为

sortedTable = { bread = 3, bike = 2, laptop = 1, lightbulb = 1 } 

有人对此有解决方案吗?

lua
1个回答
0
投票

这可能与另一个表:

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 }

© www.soinside.com 2019 - 2024. All rights reserved.