[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Self-awareness of functions?
- From: Dirk Laurie <dpl@...>
- Date: Wed, 29 Dec 2010 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.
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
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.
But wait! I'm willing to live with reserving the word "self".
Define once:
function recursive(def)
local self
[[ return the result of all sorts of clever stuff involving
string.gsub() and loadin() ]]
end
and then the anonymous function can be created by
recursive"(x) if x<2 then return 1 else return x*self(x-1) end"
But I've discovered that I am not clever enough to write that stuff :-(
Dirk
- Follow-Ups:
- Re: Self-awareness of functions?, steve donovan
- Re: Self-awareness of functions?, Drake Wilson
- Re: Self-awareness of functions?, Wim Couwenberg
- Re: Self-awareness of functions?, Michal Kolodziejczyk
- Re: Self-awareness of functions?, Dirk Laurie
- Re: Self-awareness of functions?, David Kastrup
- Re: Self-awareness of functions?, Eike Decker
- Re: Self-awareness of functions?, Luis Carvalho
- Re: Self-awareness of functions?, Henk Boom
- Re: Self-awareness of functions?, Luis Carvalho