-
Notifications
You must be signed in to change notification settings - Fork 11
/
player_cache.lua
105 lines (78 loc) · 1.86 KB
/
player_cache.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
104
105
-- from incredible-gmod.ru with <3
-- https://github.com/Be1zebub/Small-GLua-Things/blob/master/player_cache.lua
local count, all, humans, bots = 0, {}, {}, {}
player.cache = {}
do -- getters
function player.cache.GetCount()
return count
end
function player.cache.GetAll()
return all
end
function player.cache.GetHumans()
return humans
end
function player.cache.GetBots()
return bots
end
end
do -- iterators
-- usage: for i, ply in player.cache.IteratorHumans() do print(i, ply) end
local iterator = ipairs(all)
function player.cache.IteratorAll()
return iterator, all, 0
end
local iterator_humans = ipairs(humans)
function player.cache.IteratorHumans()
return iterator_humans, humans, 0
end
local iterator_bots = ipairs(bots)
function player.cache.IteratorBots()
return iterator_bots, bots, 0
end
end
do
local map = {}
local function Initialize(ply)
count = count + 1
local mapping = {}
mapping.all = table.insert(all, ply)
if ply:IsBot() then
mapping.bots = table.insert(bots, ply)
else
mapping.humans = table.insert(humans, ply)
end
map[ply] = mapping
end
for _, ply in ipairs(player.GetAll()) do
Initialize(ply)
end
hook.Add("OnEntityCreated", "player.cache.*", function(ply)
if ply:IsPlayer() then
Initialize(ply)
end
end)
local iter = {
all = player.cache.IteratorAll,
humans = player.cache.IteratorHumans,
bots = player.cache.IteratorBots
}
local function Remove(name, cache, index)
table.remove(cache, index)
for i, ply in iter[name]() do
map[ply][name] = i
end
end
hook.Add("EntityRemoved", "player.cache.*", function(ply)
if ply:IsPlayer() and map[ply] then
count = count - 1
local mapping = map[ply]
Remove("all", all, mapping.all)
if mapping.bots then
Remove("bots", bots, mapping.bots)
else
Remove("humans", humans, mapping.humans)
end
end
end)
end