lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I can't say what the "Typical Lua" way of doing this is, but as a
general point of view I can say that with some knowns this becomes a
trivial process not requiring recursion.

Knowns:
  1) Indexing is done with a numerical method (IE: You don't use
MyTable['MyIndex'] instead you use MyTable[1]..MyTable[n] where n is
the largest element)
  2) Indexing has no breaks (see #1, basically you don't go 1, 2, 5, 6,
7 instead you have 1, 2, 3, 4, 5, 6, 7)
  3) Processing happens in a depth first aproach

If these are true then you can do something as follows (untested)

input = {MyVal1, MyVal2, MyVal3}
output = {}
function Process(AnInput, AnOutput, n=1, m=2)
  local processStack = {}
  table.insert(processStack,1)
  while table.getn(processStack)>0 do
    local tblIndex = processStack[table.getn(processStack)]
    AnOutput[tblIndex] = AnInput[tblIndex]
    table.remove(processStack,tblIndex)
    if (AnInput[tblIndex]~=nil) then
      if (... test AnOutput[tblIndex]) then
        table.insert(processStack, tblIndex+m)
      else
        table.insert(processStack, tblIndex+n)
      end
    end
  end
end
Process(input, output)

Using this method should lower the Lua stack overhead and produce a
lower running cost overall.  Of course you MUST make sure that the
first if statement tests to make sure that the index is vald, this may
involve editing the line "if (AnInput[tblIndex]~=nil) then" quite a
bit.

 - Jeremy

"Help I suffer from the oxymoron Corporate Security."


> -------- Original Message --------
> Subject: lua idiom: iteration with skips?
> From: Gregg Reynolds <dev@arabink.com>
> Date: Wed, April 19, 2006 11:49 am
> To: lualist <lua@bazar2.conectiva.com.br>
> 
> Hi,
> 
> I need to iterate over a list of items with skip logic.  For example, if
> item[i] fits some criteria, then skip to item[i+n] else skip to item[i+m].
> 
> If I understand the manual, altering an iteration variable is a no-no,
> so I can't use a for loop for this.
> 
> So here's what I come up with using recursion in psuedo-code:
> 
> input = { ... }
> output = { ... }
> function process(i)
>   ... use input[i] to update output[i]
>   if ( ... test output[j]... ) then
>      process(i+m)
>   else
>      process(i+n)
>   end
> process(1)
> 
> or the like.  (I haven't tested this yet.)  My question is, what is the
> natural, idiomatic way to do this sort of thing in lua?  I'm new to it,
> so I want to learn the lua way.
> 
> -gregg