[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Self-awareness of functions?
- From: Drake Wilson <drake@...>
- Date: Wed, 29 Dec 2010 00:40:48 -0700
Quoth Dirk Laurie <dpl@sun.ac.za>, on 2010-12-29 09:22:36 +0200:
> 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.
Note that those first two are compressible into a « local function »
definition, and the do/end is only necessary if you care about the
local name being invisible afterwards, so really it's more like:
local function identity(...) return ... end
foo.identity = identity
> Trouble is, I can't see a way to write a C function "self" that
> can be imported into the global namespace and would achieve this.
> "self" would have to be an implicitly defined local variable
> referring to the function under construction, created by the Lua
> compiler: in effect, a reserved word.
I wouldn't do it that way. If it were necessary, I'd add the Y
combinator, something like (untested):
function y(f)
local function g(...) return f(g, ...) end
return g
end
and then for your example:
y(function(rec, x) if x < 2 then return 1 else return x * rec(x-1) end end)
(Of course you probably wouldn't call it 'y' in practice even though
the combinator is named that.)
I wouldn't normally bother doing that, though; I tend to give all
local recursive function definitions names anyway, for clarity.
---> Drake Wilson