首页 文章

保存lua表中的字符串索引(数组或字典表?)

提问于
浏览
-1

所以我陷入了两难境地 . 我有一个代码读取某个msg,例如:

m.content:sub(1,8) == 'Loot of ' then

内容如下:

01:50 Loot of a starving wolf: a dirty fur, a salad, 2 pancakes, 60 gold

现在我想把它插入表中 . 到目前为止我遇到的问题是我无法计算字符串的类型并在表中对它进行比较以添加其索引 .

例如:

t = {dirty fur="quantity of msgs that show this",insert a new msg="how many times haves appear}

到目前为止我的工作是:

foreach newmessage m do
m.content:sub(1,8) == 'Loot of ' then

然后我就迷失了 . 我不知道如何创建这个表;它应该是本地的,我相信,但我遇到的主要问题是我不想成对打印它,我想按照它们插入的顺序将值从1调用到#table . 这就是我的痛苦开始的地方 .

我想要的东西:

table msgs = {spear='100',something='2', ovni='123'}

所以当我得到这个表(我仍然无法制作)时,我可以为同一个表调用另一个函数,我想调用表 . “xmsg”=数量 . 我希望有人理解我的要求 .

function loot()
foreach newmessage m do
        if m.type == MSG_INFO and m.content:sub(1,8) == 'Loot of ' then
        local content = (m.content:match('Loot of .-: (.+)')):token(nil,', ')
        for i,j in ipairs(content) do
       return content
         end
      end
   end
end

返回此函数的消息:

{"3 gold coins"}
{"3 gold coins"}
{"nothing"}
{"6 gold coins", "a hand axe"}
{"12 gold coins", "a hand axe"}

1 回答

  • 1
    TEST_LOG = [[
    01:50 Loot of a starving wolf: a dirty fur, a large melon, a cactus
    02:20 Loot of a giant: a large melon, an axe
    03:30 You are on fire! Not really, this is just a test message
    04:00 Loot of a starving wolf: a dirty fur, a tooth, a bundle of hair
    04:00 Loot of a starving wolf: a dirty fur, a tooth, an axe
    ]]
    
    ENEMY_LOOT_COUNTS = {}
    LOOT_COUNTS = {}
    
    for line in string.gmatch(TEST_LOG, "([^\n]+)\n") do
        local time, msg = string.match(line, "(%d%d:%d%d) (.+)$")
        if msg and msg:sub(1, 8) == "Loot of " then
            local enemy_name, contents = string.match(msg, "^Loot of a ([^:]+): (.+)$")
            local enemy_t = ENEMY_LOOT_COUNTS[enemy_name]
            if not enemy_t then
                enemy_t = {}
                ENEMY_LOOT_COUNTS[enemy_name] = enemy_t
            end
            local items = {}
            for item_name in string.gmatch(contents, "an? ([^,]+)") do
                items[#items+1] = item_name
                enemy_t[item_name] = (enemy_t[item_name] or 0)+1
                LOOT_COUNTS[item_name] = (LOOT_COUNTS[item_name] or 0)+1
            end
        else
            -- you can handle other messages here if you want
        end
    end
    
    for enemy_name, loot_counts in pairs(ENEMY_LOOT_COUNTS) do
        local s = "Enemy "..enemy_name.." dropped: "
        for item_name, item_count in pairs(loot_counts) do
            s = s..item_count.."x "..item_name..", "
        end
        print(s)
    end
    
    do
        local s = "Overall: "
        for item_name, item_count in pairs(LOOT_COUNTS) do
            s = s..item_count.."x "..item_name..", "
        end
        print(s)
    end
    

    对于这段代码,我想写一个很长的答案,但我现在没有时间,抱歉 . 我稍后再做 .

相关问题