[lua]
count = count + 1
for i=-1,1,1 do
for j=-1,1,1 do
if (i ~= 0) or (j~=0) then
if i==0 or j==0 or (j==-1 and odd ==0) or (j==1 and odd==1) then
if (isNewConnection(row2+i, col2+j)) then
–if the bubbles row is 0, it means they are connected
if row2+i == 0 then
connArray2[0] = “connected”
else
–if not, continue to check
getConnections(row2+i, col2+j,connArray2)
end
end
end
end
end
end
[/lua]
There are a couple of things I would do. This seems like it’s where most of the processing is happening and it’s a recursive call, so being as optimal here is a place where it’s important.
First table.insert() is a costly call but it seems to be happening only once per function call, but you’re iterating over the whole list, so it does get executes a fair number of times. See this blog post:
http://www.coronalabs.com/blog/2013/03/12/performance-optimizations/
It talks about alternatives for table.insert. See #3. It looks like you’re just appending to the end of the table, so no need to traverse that table every time.
Next is those nested for loops. You really only care about -1, -1; -1, 1; 1, -1 and 1, 1 if I read your code right. You spend a lot of time testing to see if you’re hitting 0, which I assume is the current position. For loops have overhead to run the loop. There is a technique called “unrolling loops” where doing:
[lua]
array[1] = 5
array[2] = 10
array[3] = 15
[/lua]
is faster than
[lua]
for i = 1, 3 do
array[i] = i * 5
end
[/lua]
Of course in that small example, it’s meaning less, but over hundreds and thousands of iterations, the loop mechanics impact performance. You could replace all of that with a series of IF statements abandoning looping over the 0’s that you’re not testing.
If you know in side that call that you are done, you could do a return true and abort the rest of the loops running. You might want to set a flag, if you need to stop the recursion too.