[Resolved] How to properly clean external modules

Hi Corona Community

As the title says: How to properly clean external modules, so it’s memory will be released and collected by the garbage collector? -> also if the module contains eventlisteners (Runtime(enterframe), touch etc.)

Thank you for the help in advance

[import]uid: 122802 topic_id: 28093 reply_id: 328093[/import]

Hi. Great question!

Ok so say your external module looks like this:

--myModule.lua  
  
local myModule = {}  
  
--manage stuff  
local function manageStuff(event)  
 --manage items  
  
 if event.phase == "began"  
 end  
  
 return true  
end  
  
function myModule:createCircle()  
 local myCircle = display.newCircle(40, 40, 10)  
  
 myCircle:addEventListener("touch", manageStuff)  
 return myCircle  
end  
local function updateStuff(event)  
 --do something  
end  
  
Runtime:addEventListener("enterFrame", updateStuff)  
  
return myModule  

Now as you said “how would I clean this up”?

you could do something like so:

--myModule.lua  
  
local myModule = {}  
  
--manage stuff  
local function manageStuff(event)  
 --manage items  
  
 if event.phase == "began"  
 end  
  
 return true  
end  
  
local myCircles = {}  
  
function myModule:createCircle()  
 local myCircle = display.newCircle(40, 40, 10)  
  
 myCircle:addEventListener("touch", manageStuff)  
  
 myCircles[#myCircles + 1] = myCircle  
  
 return myCircle  
end  
local function updateStuff(event)  
 --do something  
end  
  
Runtime:addEventListener("enterFrame", updateStuff)  
function myModule:cleanUp()  
 Runtime:removeEventListener("enterFrame", updateStuff)  
  
 for i = 1, #myCircles do  
 myCircles[i]:removeEventListener("touch", manageStuff)  
 end  
end  
  
return myModule  

Then when you want to clean up the module you can do

--Fileyour using the functions in  
local myMod = require("myModule")  
  
--Clean up myModule  
myMod:cleanUp()  

Hope this helps!
[import]uid: 84637 topic_id: 28093 reply_id: 113653[/import]

Thanks for a great explanation Danny, I’ve been thinking about this all day and just stumbled across your post while I was browsing for another issue :slight_smile: [import]uid: 105707 topic_id: 28093 reply_id: 114631[/import]

@EHO: Your welcome :slight_smile: [import]uid: 84637 topic_id: 28093 reply_id: 114781[/import]