lua-users home
lua-l archive

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


> If I use a function to recursively traverse a graph (or tree), it appears
> that I must make that function global.  Is that true?

Yes. Local functions cannot be recursive. (Most languages need a special
feature to allow recursive local definitions, such as "letrec".)


> Is it possible to create a library function "this()" that returns
> the function that is currently running?

You can do that with the standard debug library (db):

  function this()
    return getstack(2,"f").func
  end

  -- example of use
  local f = function (n)
    if n==0 then return 1
    else return n*this()(n-1)
    end
  end

  print(f(10))
  
-- Roberto

PS: the 2 in the call to `getstack' is the function level: Level 0 is
`getstack' itself, level 1 is function `this', and level 2 is who is
calling `this'.