Environment

Lua provides an easy and powerful method to set the global environment per function. This means that any variables without the local modifier will be recorded in the environment of the function, rather than in the global table. This can be achieved by setting the _ENV variable inside a function.

The _ENV variable, by default, points to _G. This means any new variable will be registered in _G. But if you declare _ENV to be a new table, for example, variables will be registered to it instead of _G:

function SayHelloCustomEnv()
local _ENV = {print=print}

foo = "hello"
local bar = "world"

print(foo .. " " .. bar)
end

function SayHelloDefaultEnv()
foo = "hello"
local bar = "world"

print(foo .. " " .. bar)
end

-- foo and bar are not in _G
SayHelloCustomEnv1();
print (foo)
print (bar)

-- foo is declared in _G
SayHelloDefaultEnv();
print(foo)
print(bar)

In the preceding code, this line is extremely important:

local _ENV = {print=print}

First, note that _ENV is declared to be local! If you don't declare it as such, _ENV for ALL functions will be overwritten. You don't want that.

Second, _ENV is not set to an empty table, it's set to {print=print}. This is important. Normally, print lives in _G. But, the function will not be able to access _G anymore. This also means that you can replace any global function with a custom one. For example:

function MyPrint(str)
print("printing: " .. str)
end

function SayHelloCustomEnv()
local _ENV = {print=print}

foo = "hello"
local bar = "world"

print(foo .. " " .. bar)
end

-- foo and bar are not in _G
SayHelloCustomEnv();
print (foo)
print (bar)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166