[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.0 and globals (long)
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 06 Mar 2003 12:48:30 -0300
The main use we see for set/getfenv (old set/getglobals) is to create
a "local static space" (option 2 of Peter Hill's message). Typically,
you use setfenv in the first lines of a package, with a call like
setfenv(1, T)
After that call, every free variable in the whole package refers to the
table T.
There are several ways to use it. As a typical example, we can start a
package with something like this:
local P = {}
setmetatable(P, {__index = _G})
mypack = P
setfenv(1, P)
Now, everything we define inside this package goes to the package
namespace. The inheritance mechanism allows us to use global names
inside the package. We can define (and use) everything in the package
without the need to add an explicit package prefix in every identifier.
Of course, we may want to pack this functionality in an auxiliary function.
Then we need indices:
function package (name)
local P = {}
setmetatable(P, {__index = _G})
_G[name] = P
setfenv(2, P)
end
With this function, we can start a new package with
package "mypack"
(Or else, we can use _REQUIREDNAME instead of a fixed name, so that
the pacakge gets the same name of the file where it lives. But this
is a separate discussion...)
Finally, you may want to impose this package discipline from outside
to a common file (as Python does):
local P = {}
setmetatable(P, {__index = _G})
mypack = P
local f = loadfile("oldlib.lua")
setfenv(f, P)
With this scheme, the "package" itself simpy defines its functions,
without any concerns about being a package.
-- Roberto