lua-users home
lua-l archive

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


On 29 December 2010 02:22, Dirk Laurie <dpl@sun.ac.za> wrote:
>
> 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 :-(

What about a utility function written purely in lua?

-----

function recursify(f)
  local function g(...)
    return f(g, ...)
  end
  return g
end

fact = recursify(function (self, n)
  if n == 1 then
    return 1
  else
    return n * self(n-1)
  end
end)

-----

(though I personally would not recommend the use of the word 'self'
here, fortunately you can name it whatever you want, since it it not
"built in")