lua-users home
lua-l archive

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


> local function bar()
>                return foo() -- can call "foo", because foo is an upvalue 
here
> end

> My workaround for this will be to query the calling 'ar' myself and 
> search the named upvals (if getinfo fails to find the name through the 
> normal mechanism). Is there any reason why this is a bad idea?

In this particular case, I don't think it will work. return foo() is 
a tailcall, so the stack frame for bar no longer exists when/if foo
blows up.

I am strongly of the opinion that if you think objects should have
names, you should name them explicitly. Lua provides some support for
this, although I admit that it may not be sufficient for what you might
want to be doing. The code I use (from memory, my Lua stuff is at home)
looks like this:

-- module naming
local names = {setmetatable({}, {__mode = "k"})

function Named(name)
  return function(val)
    if val then names[val] = name end
    return val
  end
end

function Register(name)
  return function(table)
    for k, v in table do
      if type(v) == ¨"function" and type(k) == "string" then
        Named(name..k, v)
      end
    end
    return Named(name, table)
  end
end

function nameOfFunc(level)
  local info = debug.getinfo(level, "f")
  if info and info.func then return names[info.func] end
-- more stuff to deal with the self parameter
end

--

Using this, unfortunately, requires changing:

  local function foo() ... end

to

  local foo; foo = Named "foo" (function() ... end)

I would find this easier to live with if it were not for the close 
parenthesis; the
rest of it is a simple preprocessor substitution. It works nicely with 
tables,
though:

-- style 1:
  local meta = Register "fancyMetaTable" {
    __index = function(t, k) ... end
    __add = function(t, a, b) ... end
  }

-- style 2:
  local meta = {}
  function meta:__index(k) ... end
  function meta:__add(k) ... end
  Register "fancyMetaTable" (meta)

HTH
Rici