lua-users home
lua-l archive

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


>"As a special case, when f is 0 setfenv changes the global environment of the running thread."

The manual is not clear. "running thread" here is the lua_State not the
the script being executed.

>Why following script prints nil?
>---
>local env = {key = "test", next = next, pairs = pairs}
>setmetatable(env, {__index = _G})
>setfenv(0, env)
>print(key)
>---

It does print nil for me as well. The reason is that a script gets its
global environment at the time it is compiled not at the time it is run.
To change the global environment of the runniong script, use 1 instead
of 0 in setfenv.

If you split the script above into 2 scripts, than it works as you expected.
Try replacing the last line with
	loadstring("print(key)")()

--lhf