Should I Refactor

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

[lua]-- 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[/lua]

It does exactly what I need it to do. But I wondered if it’s okay to have the majority of my code sitting in a loop. Is it better to create a function to host the majority, and then call it in the loop somehow?

Sorry. Still new at this. But I want to make it as easy as possible so I can use the letters in the “letter” table somewhere else in the code, without having to stay in the loop. Unless it’s okay to stay in the loop, in which case, please let me know. :slight_smile: [import]uid: 14084 topic_id: 6687 reply_id: 306687[/import]

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. [import]uid: 12108 topic_id: 6687 reply_id: 23344[/import]

Sweet! Thanks again jhocking. [import]uid: 14084 topic_id: 6687 reply_id: 23440[/import]