lua-users home
lua-l archive

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


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