-
Notifications
You must be signed in to change notification settings - Fork 11
/
fcache.lua
96 lines (80 loc) · 2.44 KB
/
fcache.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
local fcache = {
_VERSION = 1.0,
_URL = "https://github.com/Be1zebub/Small-GLua-Things/blob/master/fcache.lua",
_LICENSE = [[
MIT LICENSE
Copyright (c) 2021 incredible-gmod.ru
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local function cacheGet(node, args)
if CurTime() <= node.time then
for i = 1, #args do
node = node.child[args[i]]
if node == nil then return end
end
return node.results
else
table.Empty(node)
end
end
local function cacheMake(node, args, results, time)
local arg
for i = 1, #args do
arg = args[i]
node.child = node.child or {}
node.child[arg] = node.child[arg] or {}
node = node.child[arg]
end
node.results = results
end
local unpack = unpack or table.unpack -- lua 5.3 compatibility
local function work(func, time, cache)
time = time or 30
cache = cache or {
time = CurTime() + time
}
return function(...)
local args = {...}
local results = cacheGet(cache, args)
if results == nil then
results = {func(...)}
cacheMake(cache, args, results, time)
end
return unpack(results)
end
end
local mt = {}
mt.__call = function(_, func, time)
return work(func, time)
end
setmetatable(fcache, mt)
--[[ deubg:
local random = fcache(math.random, 2)
local start = SysTime()
local function debug(repeats)
repeats = repeats - 1
if repeats <= 0 then return end
print(math.Round(SysTime() - start, 1) ..": ".. random(1, 5))
timer.Simple(0.5, function()
debug(repeats)
end)
end
debug(20)
]]--
return fcache