local function read_log() local log = io.open("log", "r") if log == nil then return function() return nil end end local lines = log:lines("l") return function() local l = lines() if l == "" or l == nil then return nil end local time, username, amount, comment = string.match(l, "(%d+),([%w_ -]+),(-?%d+),([%w_ -]*)") return tonumber(time), username, tonumber(amount), comment end end local function balances() local users = {} for _, username, amount, _ in read_log() do users[username] = (users[username] or 0) + amount end return users end local newlog = io.open("log_collapsed","w+") if newlog == nil then return print("error failed to open log") end for username, amount in pairs(balances()) do newlog:write(string.format("%d,%s,%d,%s\n", os.time(), username, amount, "Collapsed transaction history")) end newlog:close()