【问题标题】:How can I get the number of times an enttry in a table was listed如何获取列出表中条目的次数
【发布时间】:2019-10-20 11:24:49
【问题描述】:

我需要找到一种方法来查看一个条目在表格中列出了多少次。

我曾尝试查看其他代码以寻求帮助,并在网上查看示例无济于事

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 次​​p>

【问题讨论】:

    标签: lua lua-table roblox


    【解决方案1】:

    这样的事情应该可以工作:

    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 变量会使 table.* 函数不可用)并修复了模式(你有未转义的 '-' ,而你的字符串有 ':') .

    【讨论】:

      【解决方案2】:

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

      看起来您的表格条目被格式化为“[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

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2020-08-04
        • 2011-02-11
        • 1970-01-01
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        相关资源
        最近更新 更多