Recently i read through http://blog.anscamobile.com/2011/09/tutorial-modular-classes-in-corona/ about modular classes in corona.
-
I’ve been playing around with it for awhile, and i can’t figure out how to create a destructor for it. Anyone have any idea on this? The reason i want a destructor is because my object has images/sprites. Currently what i did was i wrote a obj:remove() function that removes the object image/sprite itself. However this doesn’t remove the table from the metatable.
-
Is the below code one way to write/simulate class correctly? Are there any downsides compared to the tutorial?
local CLASS = {}
-------------------------------------------------
local function create( name, health, mana )
local obj = display.newGroup()
local image = display.newImage( name .. ".png" )
obj:insert( image )
image = nil
obj.name = name
obj.health = health
obj.mana = mana
-------------------------------------------------
-- Private Methods
-------------------------------------------------
local function removeObj()
display.remove( obj )
obj = nil
end
-------------------------------------------------
local function attacked( event )
if event.phase == "ended" then
obj.health = obj.health - 1
print( obj.name .. "'s HP: " .. obj.health )
if obj.health \<= 0 then
removeObj()
end
end
end
obj:addEventListener( "touch", attacked )
-------------------------------------------------
-- Public Methods
-------------------------------------------------
function obj:setPos( x, y )
self.x = x
self.y = y
end
-------------------------------------------------
function obj:printInfo()
print( "Name:" .. self.name )
print( "HP:" .. self.health )
print( "Mana:" .. self.mana )
print( "-------------------" )
end
-------------------------------------------------
function obj:modHealth( value )
self.health = self.health + value
end
function obj:modMana( value )
self.health = self.health + value
end
function obj:remove()
removeObj()
end
-------------------------------------------------
return obj
end
-------------------------------------------------
CLASS.create = create
-------------------------------------------------
return CLASS
Thanks in advance. [import]uid: 74723 topic_id: 27256 reply_id: 327256[/import]