lua-users home
lua-l archive

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


> In Lua you must take care if you want to define a global recursive 
> function.  Thus:
> 
> do  local fact
>     fact = function(x) if x<2 then return 1 else return x*fact(x-1) end end
>     fac = fact
>     end
> fact = "Napoleon escaped from Elba."
> print(fac(5)) --> 120
> 
> You can't omit any of that padding: create a local variable, then 
> assign it to a global variable, all in an enclosing block.
> 
> Because of the need for a local name for the function, you can't define
> an anonymous recursive function, e.g. for use in an argument list.  
> 
> A standard name like "self" which makes the function aware of itself,
> would be useful:
<snip>

What about this?

  fact = function (n)
    if n < 2 then return 1 end
    local self = debug.getinfo(1, "f").func
    return n * self(n - 1)
  end

Cheers,
Luis

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso

-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'