Feel free to copy it and test it in corona.
What i am trying to do here is to create a module that creates objects with event listeners.
Memory usage seems to go up a bit, but i am not sure how that is calculated. Sometimes it just falls back. Texture memory is not leaking though.
My main concern is whether i removed the listener for the object when i call myObj:removeSelf().
To test this:
- Try touching screen once to create a red square randomly on screen
- Then wait 5 seconds for it to be remove, notice the memory used (not texture)
- After that, touch the screen 3 times to create 3 red squares.
- Then wait 5 seconds for it to be remove, the memory used increased ]:
Code:
-- main.lua
local oc = require "oc"
local function garbagePrinting()
collectgarbage("collect")
local memUsage\_str = string.format( "memUsage = %.3f KB", collectgarbage( "count" ) )
print( memUsage\_str )
local texMemUsage\_str = system.getInfo( "textureMemoryUsed" )
texMemUsage\_str = texMemUsage\_str/1000
texMemUsage\_str = string.format( "texMemUsage = %.3f MB", texMemUsage\_str )
print( texMemUsage\_str )
end
local function test( event )
if event.phase == "ended" then
print( "========================" )
print( "Before creating object:" )
garbagePrinting()
print( "========================" )
local myObj = oc.createObject( "redsquare" )
print( myObj.actions[1] )
myObj.x = math.random( 32, display.contentWidth - 32 )
myObj.y = math.random( 32, display.contentHeight - 32 )
print( "========================" )
print( "After creating object:" )
garbagePrinting()
print( "========================" )
local function removeObj()
myObj:removeSelf()
print( "========================" )
print( "After removing object:" )
garbagePrinting()
print( "========================" )
end
timer.performWithDelay( 5000, removeObj )
end
return true
end
Runtime:addEventListener( "touch", test )
-- object creator (oc.lua)
local OC = {}
--private
local function testTouch( event )
if event.phase == "ended" then
print( "touched" )
end
return true
end
--public
local function createObj( objName )
local obj = display.newGroup()
local image = display.newImage( objName .. ".png" )
obj:insert( image )
obj.actions = { "collect", "eat", "cancel" }
obj:addEventListener( "touch", testTouch )
return obj
end
OC.createObject = createObj
return OC
If i am leaking any where please let me know as i want to convert this to handle something huge.
Thanks for your time. [import]uid: 74723 topic_id: 26215 reply_id: 326215[/import]