在Lua表中保存字符串的索引(是数组还是字典表?)

我有一个棘手的问题。我的代码读取某个消息,例如:

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="显示此消息的数量",插入一个新的消息="出现次数}

到目前为止我已经可以:

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

之后我就迷失了。我不知道如何创建这个表格,它应该是本地的,我相信,但我在这方面最大的问题是,我不想将其打印成一对,我想以插入它们的顺序以从1到#table的值调用它们。这是我的痛苦之所在。

我希望像这样:

table msgs = {长矛='100',某物='2',飞碟='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枚金币"}
{"3枚金币"}
{"无"}
{"6枚金币", "一把手斧"}
{"12枚金币,一把手斧"}

原文链接 https://stackoverflow.com/questions/8397399

点赞
stackoverflow用户837856
stackoverflow用户837856
TEST_LOG = [[
01:50 饥饿的狼掉落物品:一块脏毛皮、一个大瓜、一棵仙人掌
02:20 巨人掉落物品:一个大瓜、一把斧头
03:30 你着火了!实际上不是,只是测试消息
04:00 饥饿的狼掉落物品:一块脏毛皮、一颗牙齿、一束毛发
04:00 饥饿的狼掉落物品:一块脏毛皮、一颗牙齿、一把斧头
]]

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_name.." 掉落物品:"
    for item_name, item_count in pairs(loot_counts) do
        s = s..item_count.." 个 "..item_name..","
    end
    print(s)
end

do
    local s = "总体情况:"
    for item_name, item_count in pairs(LOOT_COUNTS) do
        s = s..item_count.." 个 "..item_name..","
    end
    print(s)
end
2011-12-06 10:04:33