[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: setfenv for the whole thread
- From: "Renato Maia" <renatofigueiro@...>
- Date: Mon, 5 Jan 2004 12:16:33 -0200
Hi everybody,
I'm having some problems to understand the semantics of 'setfenv' function
(I've read some previous messages posted about similar subjects but I couldn't
figure it out). I'd like to set the global environment of a whole coroutine
thread to some table I own. According to Lua manual this is possible by
calling 'setfenv(0, my_environ)' (unless I'm horribly mistaken), but in
the following example I couldn't get the desired behavior, since neither
the coroutine thread main function nor other called functions seems to see
the environment I set previously. However some default Lua functions like
the 'print' function seems to be aware of the defined environment.
--------------------------------------------------------------------
-- Example
var = "global"
local old = tostring
local context = {
var = "local",
tostring = function(val) return "#" .. old(val) .. "#" end,
print = print,
}
local function run(func)
local thread = coroutine.create(
function()
setfenv(0, context)
print(var) -- runs with 'context' as its environment
return var, func() -- run with original global environment
end
)
return coroutine.resume(thread)
end
print(run(function() return var end))
--------------------------------------------------------------------
By the example above I expected to have the following output:
> #local#
> true local local
but I got...
> #global#
> true global global
Does anybody could please tell me what to do to get what I want?
Thanks everybody,
Renato Maia.