lua-users home
lua-l archive

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


It was thus said that the Great Thiago L. once stated:
> Hi,
> 
> I had this function:
> 
> local function myfunc(a,b)
>   -- some code here
>   x = myfunc(y,z)
>   -- more code here
>   return v
> end
> 
> Then I changed the name of the function:
> 
> local function dothing(a,b)
> 
> But I forgot to change the body!
> 
> To avoid having to change the function body every time (and to be able 
> to call itself when using local name = function(args)), I propose an 
> operator or keyword or something that returns the same value as 
> "debug.getinfo(1,'f').func"...
> 
> "What should it be?" good question... I'm not sure... I'd use "self" but 
> that's reserved by the :func() syntax sugar... "function.self" seems 
> interesting but weird/'not-lua'...


  I think what you want is known as the Y-combinator.  

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

local dothing = Y(function(me,a,b)
  -- some code here
  x = me(a,b)
  -- more code here
  return y
end)

--oh, and ... 

print(Y(function(rec, x) if x < 2 then return 1 else return x * rec(x-1) end end)(5))

  -spc (Or you could define Y() to call debug.getinfo(2,'f').func for you ... )