lua-users home
lua-l archive

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


> -------- Original Message --------
> Date: Wed, 29 Dec 2010 10:22:22 +0200
> From: Dirk Laurie <dpl@sun.ac.za>
> Subject: Re: Self-awareness of functions?
> To: Lua mailing list <lua-l@lists.lua.org>
> Message-ID: <20101229082222.GB3254@rondloper>
> Content-Type: text/plain; charset=us-ascii
> 
> On Wed, Dec 29, 2010 at 09:37:47AM +0200, steve donovan wrote:
> > On Wed, Dec 29, 2010 at 9:22 AM, Dirk Laurie <dpl@sun.ac.za> wrote:
> > > 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
> > 
> > But this use of self is immediately going to conflict with implicit
> > self generation in methods.
> > 
> Then use a different word, say "recurse".
> 
> > How about just this?
> > 
> > local fact
> > function fact(n)
> >    if n == 2 return 2 else return n*fact(n-1) end
> > end
> > 
> > Works because the statement  'function F(...)' is sugar for 'F =
> > function(...)'  and so is just assigning to a predeclared local
> > variable.
> >
> Maybe first try your code under the interactive environment before
> posting ... but OK, we all don't :-)  But assuming that you wrote 
> what you thought you did, try this:
> 
> fac = fact
> fact = "Napoleon escaped from Elba."
> fac(5)
> 
> That's why my version is more complicated.
> 
> Dirk

I'm not sure what you were trying to get at here. What Steve wrote had a
typo (missing keyword "then"), but was otherwise correct. It should have
been this:

local fact
function fact(n)
    if n == 2 then return 2 else return n*fact(n-1) end
end

However, typing that directly into the console as-is will not do what
you expect because each input line is processed independently -- locals
only survive the one line they appear on. The fact() function ends up
being global, not local.

The above code works if placed on a single line. Any use of fact() [e.g.
print(fact(5))] needs to be on the same line. The line is too long to
post, so here's a shorter version of essentially the same thing that
works on one line.

local f;function f(n) return n==2 and 2 or n*f(n-1) end;print(f(5))

I prefer this equivalent version:

local function f(n) return n==2 and 2 or n*f(n-1) end;print(f(5))

After running this line, function f is no longer visible to the console
because the local f is no longer in scope (try typing "print(f)" or
"f(6)" at the console).

John Giors
Independent Programmer
Three Eyes Software
jgiors@ThreeEyesSoftware.com
http://ThreeEyesSoftware.com