lua-users home
lua-l archive

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


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 also doesn't work in some cases such as tail calls, since
the local no longer exists by the time you parse the string.

Otherwise you can also pass all the locals as a table like:
string.vsub("foo = $foo, bar = $bar", {foo=foo, bar=bar}) --or:
string.vsub("foo = $1, bar = $2", {foo, bar})
but that repeats the variable names at least twice (thrice if you want
to name them in the string itself).

Perhaps in 5.2 you can pass _ENV? I'm still not totally clear on how that works.

-- 
Sent from my toaster.