lua-users home
lua-l archive

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


On 4/19/06, Gregg Reynolds <dev@arabink.com> wrote:
> 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'd like to point out that Lua is propery tail recursive, so if you
replace the line "process(i+m)" with "return process(i+m)" and so on,
the Lua virtual machine will be able to run your program without any
additional stack overhead.  (I am assuming you meant to put an "end"
before "process(1)", so that the recursive call was the very last
thing executed in your function.)

Using tail recursion is a fine way to solve a problem.  Be careful,
though; some things that look like tail calls aren't.  Refer to the
manual at
  http://www.lua.org/manual/5.1/manual.html#2.5.8
paying close attention to the examples at the end of the section.

Note that I probably would have solved your problem with a repeat
loop, something like (untested code follows):

local i=1
repeat
  ... use input[i] to update output[i]
  if ( ... test output[i] ... ) then
    i=i+m
  else
    i=i+n
  end
until
  ??? (you never specified your exit condition)

But there's nothing wrong with using recursion here.

Greg F