The downside to creating a module's basic approach is that it's easy to pollute the global space by forgetting to use local.
The "Functional environment" is an interesting technique that solves the problem above. is to have the main block of the module monopolize an environment.
So not only does all of its functions share this table, but all its global variables are also recorded in this table. You can also declare all public functions as global variables.
This allows them to be automatically recorded in a separate table. What the module does is to give this table the module name and package.loaded:
Local m = {}_env = mfunction Add (c1,c2) return new (C1,r + C2.R, c1.i + c2.i)End
When we declare the Add function, it automatically goes to the M.add. When other functions are called in the module, the prefix is no longer needed, and new will look for m.new.
This makes it possible to call an exported function with a private function without any distinction. Even forgetting to write local does not pollute the global namespace, it only turns a private function into public.
But here's the problem: we changed the _ENV environment variable, which prevented us from accessing the previous global variables.
Here are a few ways to solve (mixed):
1 "Inheritance
Local m = {}setmetatable_g})_env = m
The module now has direct access to the global identifier, which requires only a small cost per visit. This approach leads to a consequence, conceptually, that the module now contains all the global variables.
For example, the sine function is called through the module:
Complex. Math.sin (x)
It feels like a little out of bounds and out of control.
2 "Save the old environment with local variables
Local m = {}local_g_g_env = M -- or _env = nil
This method must precede the names of all global variables with "_g", which is faster than the previous method because there is no meta-method involved.
3 "Load only the required modules or functions (in the same way as local variables)
--Module SettingsLocalM = {}--Import section: Importing Segments--declare everything this module needs from outside--declare everything that this module needs to be introduced from the outsideLocalsqrt =math.sqrtLocalIO =io--no more external access after this point--after that, no external access is needed._env=Nil --or _env = M
This approach is more formal, but this technique requires more work, but it clearly illustrates the dependencies of the modules.
At the same time, it runs faster than the previous two methods and should use the local variable for it.
The above:the second edition of LUA programming and the programming in Lua Third edition
Chapter 15_3 Use Environment