-
Notifications
You must be signed in to change notification settings - Fork 4
/
Transactions.lua
103 lines (87 loc) · 2.46 KB
/
Transactions.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
local Transactions = {}
function Transactions.Init()
local self = {
d = {}
}
local Pattern = {
AllStats = "[^\n]+",
LatestStat = "[%a%d\;]+\n$",
ByTimestamp = "[%a%d\;]+\n",
StringToTransaction = "[^;]+"
}
function self:LoadData(_data)
self.d = _data
end
function self:GetAllTransactionsForItemId(itemid)
local transactions = {}
if self.d[itemid] ~= nil then
local lines = string.gmatch(self.d[itemid].data, Pattern.AllStats)
for line in lines do
local transaction = stringToTransaction(line)
transactions[transaction.timestamp] = transaction
end
end
return transactions
end
function self:GetTransactionByItemIdAndTimestamp(itemid, timestamp)
if self.d[itemid] ~= nil then
local line = trim(string.match(self.d[itemid].data, tostring(timestamp) .. Pattern.ByTimestamp))
if line == "" or line == nil then
return nil
end
return stringToTransaction(line)
else
return nil
end
end
function self:RemoveTimestamp(itemid, timestamp)
self.d[itemid].data = string.gsub(self.d[itemid].data, tostring(timestamp) .. Pattern.ByTimestamp, "")
end
function self:SaveTransaction(itemid, stat, prepend)
if self.d ~= nil then
if self.d[itemid] == nil then
self.d[itemid] = {}
self.d[itemid].data = ""
end
if prepend ~= true then
self.d[itemid].data = self.d[itemid].data .. transactionToString(stat)
else
self.d[itemid].data = transactionToString(stat) .. self.d[itemid].data
end
end
end
function transactionToString(transaction)
-- concat with '..' is very slow in lua due to immutable strings. Using a table is the recommended way for large volumes
local t = {}
t[1] = transaction.timestamp or ""
t[2] = transaction.quantity or 0
t[3] = transaction.price or 0
t[4] = transaction.result or 0
t[5] = '\n'
return table.concat(t, ";")
end
function stringToTransaction(input)
local t = iteratorToArray(string.gmatch(input, Pattern.StringToTransaction))
local transaction = {}
transaction.timestamp = tonumber(t[1])
transaction.quantity = tonumber(t[2])
transaction.price = tonumber(t[3])
transaction.result = tonumber(t[4])
return transaction
end
function iteratorToArray(iterator)
local arr = {}
for v in iterator do
arr[#arr + 1] = v
end
return arr
end
function trim(s)
if s == nil then
return nil
end
return s:find'^%s*$' and '' or s:match'^%s*(.*%S)'
end
return self
end
Apollo.RegisterPackage(Transactions, "CommodityStats:Transactions", 1, {})