I am trying to use Lua source files for configuration purposes, but I do not want the configuration files to pollute the global namespace.
The problem I am facing is that it dofilealways runs in a real global environment, so external files just throw all their declarations into _G.
Here is an example of the main file with comments indicating my wishful thinking.
function myFunc()
print("In the sandbox:")
print("Should be 1:", a) -- falls back to _G for lookup
a = 2 -- instantiating new global for sandbox
print("Should be 2:", a) -- from sandbox
print("Should still be 1:", _G.a) -- from host environment
dofile("loading.lua") -- here where things go wrong
print "\nBack in the sandbox:"
print("Should be 3:", a) -- changed by loadfile
print("Should STILL be 1:", _G.a) -- unchanged
end
a = 1
local newgt = {} -- new environment
setmetatable(newgt, {__index = _G})
setfenv(myFunc, newgt)
myFunc()
print("\nOutside of the sandbox:")
print("Should be 1: ", a) -- in theory, has never changed
And the download file ( loading.lua:
print ("\nLoading file...")
print("Should be 2: ", a) -- coming from the sandbox environment
a = 3
print("Should be 3: ", a) -- made a change to the environment
And finally, the conclusion that I see:
In the sandbox:
Should be 1: 1
Should be 2: 2
Should still be 1: 1
Loading file...
Should be 2: 1
Should be 3: 3
Back in the sandbox:
Should be 3: 2
Should STILL be 1: 3
Outside of the sandbox:
Should be 1: 3
source
share