[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua Basics: function environments and function parameters?
- From: Rici Lake <lua@...>
- Date: Thu, 25 Aug 2005 16:02:23 -0500
On 25-Aug-05, at 3:33 PM, William Trenker wrote:
I've been experimenting with introspection in Lua (5.0.2). If I
understand correctly, a function's parameters are not included in that
function's environment table. For example:
That's correct. They are local variables.
What I find curious is what happens when I redfine the function in the
same chunk:
You've set p in the global environment.
The environment table is just a table; when a function closure is
created, it is created with the same environment table as its creator
(*not* a copy of the table):
------------------------ chunk -----------------------
function f(p) -- same as previous chunk
local env = getfenv(1)
-- env is now the global environment
setmetatable(env, {__index=_G})
env.p = p
-- so this sets p in the global environment
setfenv(1, env)
print(string.format("<%s>: p = %s", tostring(f),p))
print(string.format("<%s>: getfenv(1).p = %s",tostring(f),
tostring(getfenv(1).p)))
end
What you probably wanted to do was:
function f(p)
local env = {} -- a new table
setmetatable(env, {__index = _G})
-- now the global environment is the "backup" for the new table
env.p = p
setfenv(1, env)
-- now the function has a different environment table
-- ...
end
The following is identical but maybe not so easy to read:
function f(p)
setfenv(1, setmetatable({p = p}, {__index = _G}))
-- ...
end