lua-users home
lua-l archive

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



On Dec 25, 2011 3:00 PM, "HyperHacker" <hyperhacker@gmail.com> wrote:
>
> On Sun, Dec 25, 2011 at 09:14, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> >>
> >> I wrote a string interpolator a while ago, but the biggest problem I
> >> found was locals and upvalues. There's no good way to look them up by
> >> name.
> >>
> >> Or I can just keep dreaming that someday Lua will provide a method to
> >> look up variables in the current local scope by name... :~)
> >>
> >
> > function locals()
> >    local t={}
> >    for i=1,20 do
> >        k,v=debug.getlocal(2,i)
> >        if k==nil then break else t[k]=v end
> >    end
> >    return t
> > end
> >
> > do local a=42; s=locals() end
> > print (s.a)
> >    42
> >
>
> That's what I do now, but it's terribly inefficient. AFAIK you can't
> just do one iteration like that; you have to keep looking at higher
> and higher levels until you hit the top of the stack. So looking up a
> local by name is an O(n^2) operation... (I'd love to be wrong about
> this!)

It is not O(n^2). It is O(n+m) where n is the number of stack frames and m is the number of locals on the stack.