-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGarbageCollector.lua
65 lines (53 loc) · 1.74 KB
/
GarbageCollector.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
local mexico = require "mexico"
--
-- GarbageCollector
--
-- Properties:
--
-- + performWithDelay [boolean] : Perform garbage collection with a 1 ms delay once per frame
--
local GarbageCollector = mexico.class(false) -- create a class without base (a root class)
function GarbageCollector:init()
if self then
self.performWithDelay = true -- delay collect garbage by default with a timer
Runtime:addEventListener("memoryWarning", self) -- listen to memory warnings
end
end
--
-- Returns the amount of memory (KB) allocated by the Lua VM runtime.
--
function GarbageCollector:memoryUsed()
return math.ceil(collectgarbage("count") + 0.5)
end
--
-- Returns the amount of allocated texture memory (KB).
--
function GarbageCollector:textureMemoryUsed()
return math.ceil((system.getInfo("textureMemoryUsed") / 1000) + 0.5)
end
function GarbageCollector:timer(event)
self:collectGarbage()
self.timerHandle = nil
end
function GarbageCollector:memoryWarning()
print("WARNING: received low memory warning from the system")
self:collectGarbage() -- collect garbage immediatly
if self.performWithDelay then
self:collect() -- and once again with with delay
end
end
function GarbageCollector:collectGarbage()
collectgarbage("collect")
print("INFO: " .. self:memoryUsed() .. " kb memory and " .. tostring(self:textureMemoryUsed()) .. " kb texture memory used after garbage collection")
end
function GarbageCollector:collect()
if self and self.performWithDelay then
if not self.timerHandle then
self.timerHandle = timer.performWithDelay(1, self)
end
else
self:collectGarbage()
end
end
-- GC is a singleton - so return an instance and not a class object
return GarbageCollector()