如何获取表中某个条目被列举的次数

我需要找到一种方法来看到一个表中某个条目列举的次数。

我已经尝试查看其他代码以获得帮助,并在网上查看示例,但它们都没有帮助

local pattern = "(.+)%s?-%s?(.+)"

local table = {"Cald_fan:1", "SomePerson:2", "Cald_fan:3","anotherPerson:4"}

for i,v in pairs(table) do
    local UserId, t = string.match(v, pattern)

    for i,v in next,UserId do
        --我试图做这样的事情
    end
end

它应该说Cald_fan被列举了2次

点赞
用户2860267
用户2860267

如果您的表格条目格式一致,您可以简单地将字符串拆分并将组件用作计数器映射中的键。

看起来您的表格条目格式为“[player_name]:[index]”,但似乎您并不关心索引。但是,如果“:”将出现在每个表格条目中,则可以编写一个相当可靠的搜索模式。您可以尝试类似于以下内容:

- 使用格式为<player_name>:<some_number>的条目列表
local entries = {"Cald_fan:1", "SomePerson:2", "Cald_fan:3","anotherPerson:4"}
local foundPlayerCount = {}

-- 遍历条目列表
for i,v in ipairs(entries) do
    -- 使用以下模式解析出玩家名和数字:
    -- (.+) = 捕获任意数量的字符
    -- :    = 匹配冒号字符
    -- (%d+)= 捕获任意数量的数字
    local playerName, playerIndex = string.match(v, '(.+):(%d+)')

    -- 使用playerName作为计数器出现次数的键
    if not foundPlayerCount[playerName] then
        foundPlayerCount[playerName] = 0
    end
    foundPlayerCount[playerName] = foundPlayerCount[playerName] + 1
end

-- 打印所有玩家
for playerName, timesAppeared in pairs(foundPlayerCount) do
    print(string.format("%s appeared %d times", playerName, timesAppeared))
end

如果您将来需要进行模式匹配,我强烈推荐阅读这篇有关lua字符串模式的文章:http://lua-users.org/wiki/PatternsTutorial

希望这有所帮助!

2019-06-04 23:43:27
用户1442917
用户1442917
以下翻译仅供参考:

```lua
-- 定义模式
local pattern = "(.+)%s*:%s*(%d+)"
-- 定义表(table)
local tbl = {"Cald_fan:1", "SomePerson:2", "Cald_fan:3","anotherPerson:4"}
-- 定义一个计数器(table)
local counts = {}

-- 循环遍历表 tbl 中的元素
for i,v in pairs(tbl) do
    -- 尝试匹配 UserId 和 t 两个变量
    local UserId, t = string.match(v, pattern)
    -- 如果 counts 数组中已经有 UserId 这个键,那么对应的值加 1;如果没有,则新建一个键并将值设为 1
    counts[UserId] = 1 + (counts[UserId] or 0)
end
-- 输出 Cald_fan 的计数
print(counts['Cald_fan']) --> 2

在这段代码中,原作者将 table 变量名改成了 tbl(因为使用 table 变量名会影响 table.* 函数的使用),并修正了模式中的错误(原来的模式中有未转义的 -,与字符串中的 : 不匹配)。

2019-06-04 23:43:46