Should I Refactor

I'm still new to Corona and Lua. I just had a question. I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- Display Constants
_H = display.contentHeight;
_W = display.contentWidth;
 
local word = "tree"
 
wordLength = string.len(word)
 
for c = 1, wordLength do
  local letter = {}
  local letter = string.sub(word, c, c)
  local letters = display.newText(letter, 0,0,"Times",76)
  letters.x = _W / 2 + (c  * 55) - 150
  letters.y = _H / 2
  
  function letters:touch(e)
            if(e.phase == "ended") then
      letters:removeSelf(self)
        end
  end
  letters:addEventListener("touch", letters)
end

Having most of that code is a loop is unavoidable because, well, it has to happen multiple times. However, the function inside the loop probably shouldn't be declared inside the loop, because that'll cause it to be created over and over. Typically you would create a function outside the loop and just call the function inside the loop.

The tricky thing here however is that your function is attached as a method of "letter" and "letter" doesn't exist until it's created in the loop. I would instead use a local function as the listener rather than a table, thus enabling you to declare the function outside the loop.

--

That all said, this is a pretty simple situation and not really worth sweating over. Yeah it could be done incrementally more efficiently, but the difference wouldn't be that great so don't lose sleep over this.

Sweet! Thanks again jhocking.

views:1201 update:2011/10/6 9:28:12
corona forums © 2003-2011