lua-users home
lua-l archive

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


Hallo,

On Tue, Apr 10, 2012 at 9:22 AM, Tim Hill <drtimhill@gmail.com> wrote:
>
> 2. Wrap the function in a closure that contains a reference to itself and recurse using the closure. Something like this:
>
> do
>        local function f1(n)
>                if n == 0 then return 1 end
>                return n * f1(n-1)
>        end
>        fact = f1
> end
>

The closure itself has its scope, so I'd do like this:

function f1(n)
   local function real_f1(y)
      if y == 0 then return 1 end
      return y * real_f1(y - 1)
   end
   return real_f1(n)
end

Cheers,
-- 
-alex
http://www.artisancoder.com/