如何获得表中条目的列出次数

时间:2019-06-04 22:40:28

标签: lua lua-table roblox

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

我尝试查看其他代码以寻求帮助,并在线查看示例,但没有帮助

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
        --I have tried something like this
    end
end

假设Cald_fan被列出2次

2 个答案:

答案 0 :(得分:0)

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

看起来您的表条目的格式为“ [player_name]:[index]”,但您似乎并不关心索引。但是,如果每个表条目中都包含“:”,则可以编写一个非常可靠的搜索模式。您可以尝试这样的事情:

-- use a list of entries with the format <player_name>:<some_number>
local entries = {"Cald_fan:1", "SomePerson:2", "Cald_fan:3","anotherPerson:4"}
local foundPlayerCount = {}

-- iterate over the list of entries
for i,v in ipairs(entries) do
    -- parse out the player name and a number using the pattern :
    -- (.+) = capture any number of characters
    -- :    = match the colon character
    -- (%d+)= capture any number of numbers 
    local playerName, playerIndex = string.match(v, '(.+):(%d+)')

    -- use the playerName as a key to count how many times it appears
    if not foundPlayerCount[playerName] then
        foundPlayerCount[playerName] = 0
    end
    foundPlayerCount[playerName] = foundPlayerCount[playerName] + 1
end

-- print out all the players
for playerName, timesAppeared in pairs(foundPlayerCount) do
    print(string.format("%s was listed %d times", playerName, timesAppeared))
end

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

希望这会有所帮助!

答案 1 :(得分:0)

类似的事情应该起作用:

local pattern = "(.+)%s*:%s*(%d+)"
local tbl = {"Cald_fan:1", "SomePerson:2", "Cald_fan:3","anotherPerson:4"}
local counts = {}

for i,v in pairs(tbl) do
    local UserId, t = string.match(v, pattern)
    counts[UserId] = 1 + (counts[UserId] or 0)
end
print(counts['Cald_fan']) -- 2

我将table重命名为tbl(因为使用table变量使表*功能不可用)并修复了模式(您在其中未转义'-'),字符串带有“:”)。