I’m trying to implement object pooling but am running into a memory issue. Every time I’m using an object from a pool and sending it back to the pool, the memory increases. But that shouldn’t be the case, should it? Since I’m reusing the same object?
Pool.lua
local pool = {} local poolmt = {\_\_index = pool} local Piece = require "Piece" local mydata = require "mydata" function pool.create(parameters) local function newObject() local obj = display.newSprite(Base, seq) obj:setFrame(newO) obj.isVisible = false function obj:reset() obj.alpha = 1 obj.rotation = 0 obj.anchorX = 0.5 obj.anchorY = 0.5 obj.x = 0 obj.y = 0 end return obj end poolSize = poolSize or 16 assert(newObject, "A function that returns new objects for the pool is required.") local freeObjects = {} for \_ = 1, poolSize do table.insert(freeObjects, newObject()) end return setmetatable({ freeObjects = freeObjects, newObject = newObject }, poolmt ) end function pool:obtain() return #self.freeObjects == 0 and self.newObject() or table.remove(self.freeObjects) end function pool:free(obj) assert(obj, "An object to be freed must be passed.") obj:scale(1, 1) obj.isVisible = false table.insert(self.freeObjects, obj) end function pool:clear() for k in pairs(self.freeObjects) do print("clear "..k) self.freeObjects[k] = nil end end return pool
Implement pool in actual code…
A button…
local closeBtn = display.newGroup() sceneGroup:insert(closeBtn) local close\_btn\_s = pools[86]:obtain() close\_btn\_s.pool = pools[86] closeBtn:insert(close\_btn\_s) close\_btn\_s.isVisible = true local close\_btn = pools[98]:obtain() close\_btn.pool = pools[98] close\_btn.isVisible = true closeBtn:insert(close\_btn) ...add touch listener to closeBtn
Removing button using a function clearSprite()
clearSprite(closeBtn)
closeBtn = nil
local function clearSprite(group) if not group then return false end if group.touch then group:removeEventListener( "touch") group.touch = nil end local n = group.numChildren if (not n) or n == 0 then if group.pool then group.pool:free(group) else group:removeSelf( ) end group = nil else for i = n, 1, -1 do local child = group[i] clearSprite(child) end end end
Hope someone could spare the time to take a look at all this stuff. I can’t figure out where I’m going wrong with this. Thanks.