lua-users home
lua-l archive

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


On Thu, 2009-10-08 at 23:44 +0100, Duncan Cross wrote: 
> On Thu, Oct 8, 2009 at 11:20 PM, Norbert Kiesel <nkiesel@tbdnetworks.com> wrote:
> > Hi,
> >
> > is it possible to get the name of a variable within Lua if I only have
> > the variable?  I want to write a small helper function logger that
> > basically prints the name and the value of the variable
> >
> > function logger(name, value) print(name, 'has value', value) end
> > foo = 'hello'
> > logger('foo', foo)
> >
> > Now I'd like to just call "logger(foo)" and get the same output.
> 
> I don't think there is any way for logger() to determine that - all it
> has is the evaluated value of foo, not some reference to the token
> 'foo'.
> 
> If you don't mind it being logger('foo') instead of logger(foo), that's doable:
> 
> do
> 
>   function logger(varname)
>     local i = 1
>     while true do
>       local lname,lvalue = debug.getlocal(2,i)
>       if (lname == varname) then
>         print(lname, "has value", lvalue)
>         break
>       elseif (lname == nil) then
>         print(varname, "has value", _G[varname])
>         break
>       end
>       i = i + 1
>     end
>   end
> 
>   globalvar = 10
>   function test()
>     local localvar = 5
>     logger('localvar')
>     logger('globalvar')
>   end
> 
>   test()
> 
> end

Thanks.  I'll try to extend it for other vars (e.g. foo.bar) as well.