使用Lua计算文件中的出现次数并重写文件。

我有一个 Lua 脚本,每次发生事件时都会将某人的名字添加到文件中的列表中。

我希望重写这个文件,以便它的出现次数或“实时”更新的文件。

这是一个例子。

Albert
Albert
Albert
Bert
Bert
Albert
Cedric
Cedric

这是由这段代码生成的

function add_stats(name)
    local f = io.open(stats_file, "a")
    local text = tostring(f:read("*all"))
    f:write("\n", name)
    f:close()
end

到目前为止,我已经能够使用以下代码计算出现次数

function get_stats(name)
    local f2 = assert(io.open(stats_file, "r"))
    local text2 = tostring(f2:read("*all"))
    local _, count = string.gsub(text2, name, "")
    f2:close()
    return name .. " = " .. count
end

但这导致统计文件被填满了无尽的代码行。

理想情况下,我希望文件看起来像这样

Albert 6
Bert 5
Cedric 9

当 Albert 触发脚本时,它应该更新到 10。

点赞