[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Self-awareness of functions?
- From: Eike Decker <zet23t@...>
- Date: Wed, 29 Dec 2010 11:27:42 +0100
2010/12/29 Dirk Laurie <firstname.lastname@example.org>:
> 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
> 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:
local function fact (x) if x<2 then return 1 else return x*fact(x-1) end end
fac = fact
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.