Safe to use Local table for Recursive function

Find quick help here to get you started with Hollywood
Post Reply
Bugala
Posts: 1178
Joined: Sun Feb 14, 2010 7:11 pm

Safe to use Local table for Recursive function

Post by Bugala »

As I tend to have a need for temporary tables inside my recursive path finding functions, I am therefore wondering could I just use Local table instead of making permanent table.

An example:

Code: Select all

Function Recursive(n, round)
	if Round>20 then return
	If hasItem(TempTable, n) then return
	TempTable[n] = true
	Recursive(n+1, round+1)
	Recursive(n*10, round+1)
endfunction
	
Local TempTable = {}
Recursive(1)
I didnt check this works, since this is anyway nonsensical example.

But point being that in this case I am using TempTable to check that same number is not being checked twice.

Making TempTable Global, will definetily work, but since this Table has no other use, but this temporary use here, then could I safely use Local here, since basically only reference to this Local table is being sent to Recursive function, so from that point of view it is safe, but is there a risk it would stop existing in middle of doing recursive functions, or a risk that some other table inside the recursive function would occupy its memory space?
User avatar
Allanon
Posts: 732
Joined: Sun Feb 14, 2010 7:53 pm
Location: Italy
Contact:

Re: Safe to use Local table for Recursive function

Post by Allanon »

Hi Bugala,
when I use recursive functions and I need to store temporary tables but shared between each "recursion" call I pass this table to the function, something like this:

Code: Select all

Function recursion(data1, data2, tempTable)
  If IsNil(tempTable)
    ; This is the first call, setup the temp table
    tempTable = {}
  EndIf

  ; Do your stuff and populate/process your tempTable and if you need recursion do this:
   tempTable = recursion(data1, data2, tempTable)
   
  ; Before calling the recursion you could check round or anything else you need to returns to the caller function.

  ; Return the processed tempTable
  Return(tempTable)
  
EndFunction
data1 and data2 are just placeholders, instead tempTable is you temporary table but shared between each recursive call, add rounds or anything else you need to limit/control the recursion.

So the first time you call that function you will do:

Code: Select all

recursion(data1, data2)
In your code sample:

Code: Select all

Function Recursive(n, round, TempTable)
        if IsNil(TempTable) Then TempTable={} ; First call, init a local table to share between recursive calls

	if Round>20 then return(TempTable)
	If hasItem(TempTable, n) then return(TempTable)
	TempTable[n] = true
	TempTable = Recursive(n+1, round+1, TempTable)
	TempTable = Recursive(n*10, round+1, TempTable)

        Return(TempTable)
endfunction

TempTable = Recursive(1)
Not tested and posted from memories but the concept should be fine.
Post Reply