[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Self-awareness of functions?
- From: Michal Kolodziejczyk <miko@...>
- Date: Wed, 29 Dec 2010 10:16:49 +0100
On 29.12.2010 08:22, Dirk Laurie wrote:
>
> In Lua you must take care if you want to define a global recursive
> function. Thus:
Why? What problems do you expect?
>
> 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:
>
> function(x) if x<2 then return 1 else return x*self(x-1) end end
So write a self-aware function (much like object:method() syntax sugar):
local myfunction=function(self, x) if x<2 then return 1 else return
x*self(self, x-1) end end
local result=myfunction(myfunction, 5)
Or use callable objects:
Fact=setmetatable({}, {__call=function(self, x) if x<2 then return 1
else return x*self(x-1) end end})
local result=Fact(5)
> 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.
I still don't see why you would need such complicated strategy. If your
recursive function is global, then it does not need to be self-aware.
If you need an anonymous self-aware function, just define one and use it
like that (maybe wrapped as a callable oject to simplify the API).
Regards,
miko