lua-users home
lua-l archive

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


2010/12/29 Dirk Laurie <dpl@sun.ac.za>:
>
> 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.

I haven't seen this being pointed out, but you can also write this a
bit shorter using the "local function abc ()" syntax:
---
do
  local function fact (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
---

it is also pointed out somewhere that the only difference between
"local x = function () end" and "local function x () end" is, that the
later encloses x in the scope where as the prior excludes it
(technically, you can write things like "local x = 5; local x =
function() return x end" and it would return 5 - whereas this won't
work with "local function x ()").

Recursion for anonymous functions still doesn't work, which is, I
agree, sometimes annoying.

Cheers,
Eike