I now realize how silly my implementation is. It will never be called for existing global variables. It should be more like:
__index=function(_,n)
local env=threadEnvironments[coroutine.running()] -- a table that keeps custom environments for select threads
return env and env[n]
end
From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On Behalf Of Ivo Beltchev
Sent: Friday, January 11, 2013 9:53 AM
To: lua-l@lists.lua.org
Subject: Per-thread environment
Hi
It looks to me from the documentation that environments are tied to a function. So any time a function is being called, it has access to that environment.
Is it possible to associate an environment with a thread instead? So if a function is executed in that thread it will use the thread’s environment.
Basically I’m trying to simulate TLS. I want any access to a TLS variable to use the local environment, but when accessing a global variable (a variable not in the current environment), I want to access the real global variable.
One way I can do this manually is to manipulate the metatable of _G:
__index=function(g,n)
local env=threadEnvironments[coroutine.running()] -- a table that keeps custom environments for select threads
if env and env[n] then
return env[n]
end
return rawget(g,n)
end
and something similar for __newindex
Is there something like that already built into the language?
Ivo