[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: getting upvalues in current thread's environment?
- From: "Matthew Armstrong" <turkeypotpie@...>
- Date: Sun, 28 Jan 2007 15:11:15 -0800
well, had to try :)
I can still use anonymous functions. It just won't be quite as pretty.
Thanks.
On 1/28/07, Rici Lake <
lua@ricilake.net> wrote:
On 28-Jan-07, at 3:56 PM, Matthew Armstrong wrote:
> Setting the environment explicitly works, but that doesn't really help
> me write the tighter syntax that I want.
> For instance, this does allow me to use the syntax I want:
>
> function getEnv()
> local env = {}
> local i = 1
> while true do
> local localVar, value = debug.getlocal(3, i)
> if localVar ~= nil then
> env[localVar] = value
> else
> break
> end
> i = i + 1
> end
> setmetatable(env, {__index = _G})
> return env
> end
>
> function eval(s)
> local f = assert(loadstring(s))
> setfenv(f, getEnv())
> f()
> end
>
> function flarp()
> local myLocal = "hello"
> eval[[print(myLocal)]]
> end
>
> flarp()
>
> (prints hello)
>
> ... but it uses the debug library and has a nice fat function call
> overhead.
... and it wouldn't work if you'd written:
function flarp()
local myLocal = "hello"
return eval[[print(myLocal)]]
end
The simple fact of the matter is that Lua locals are ephemeral
anonymous stack slots. So it's not going to work the way you want it
to, I'm afraid.
(The changed flarp doesn't work because eval is tailcalled, which
allows Lua to recycle the stack frame; consequently, myLocal no longer
exists.)