Hi again. It’s a morning of odd topics for me. In this post, I’m looking for community input on an idea I’m having trouble with.
I am writing a small tutorial on ‘best practices’ and in this writing I’ve become stuck describing a feature of Corona that I use regularly.
In Corona, a number of functions take a function reference OR an object reference, as long as that objects has a specially named field, referencing an appropriate function.
For example, you can write this:
local obj = display.newCircle( 240, 160, 30 ) timer.performWithDelay( 500, function() print( "x:" .. obj.x, "y:" .. obj.y) end, -1 )
, or you can write this:
local obj = display.newCircle( 240, 160, 30 ) obj.timer = function( self, event ) print( "x:" .. self.x, "y:" .. self.y ) timer.performWithDelay( 500, obj ) end timer.performWithDelay( 500, obj )
, which is better. Of course, this is the best (safest):
local obj = display.newCircle( 240, 160, 30 ) -- Safely stops when display object has been deleted obj.timer = function( self, event ) if( self.removeSelf == nil ) then return end print( "x:" .. tostring(self.x), "y:" .. tostring(self.y), "@" .. tostring(event.time) .. " ms" ) print("-------------\n") timer.performWithDelay( 500, self ) end timer.performWithDelay( 500, obj ) -- Delete obj in 1.75 seconds to show this is safe timer.performWithDelay( 1750, function() display.remove( obj ) end )
Closure Fields
Before we get distracted by what I did above, let me draw you back to the topic. The question at hand is, “What should I call that field?” i.e. ‘obj.timer’
There are lots of these:
- obj.timer - As shown, used for timers.
- obj.touch - For touches.
- obj.tap - For taps.
- obj.onComplete - For transition.to( obj, { onComplete = obj } )
- … etc.
Some of these are used for ‘listeners’ others are used for closures (as in the case of ‘timer’). Because, you can consider some coding cases for listeners to be a sub-set of closures, I’m thinking that calling these ’ closure fields’ makes the most sense.
Please, give me your input if you have any ideas on this. Also, if there already exists a name for this and I was so silly as to miss it, please let me know.
Kudos and thanks to all who particpate!
Oh, and you can see more examples of ‘closure fields’ HERE.