luaenvlua-5.2lua-loadfile

Loading a file and returning its environment


I'm attempting to do the following : (include() code below)

File1.lua

A = 5

File2.lua

file1 = include(File1.lua)
A = 1

print(A) -- 1
print(file1.A) -- 5

i've found exactly what i'm looking for but in lua 5.1 here : Loadfile without polluting global environment

But i just can't get it to work in 5.2,

function include(scriptfile)
local env = setmetatable({}, {__index=_G})
assert(pcall(setfenv(assert(loadfile(scriptfile)), env)))
setmetatable(env, nil)
return env 
end

Using this from C++, with a registered version of loadfile, so i'm trying not to modify the function call.Is this possible? Whatever i try breaks or env is null.


Solution

  • File2.lua

    function include(scriptfile)
        local env = setmetatable({}, {__index=_G})
        assert(loadfile(scriptfile, 't', env))()
        return setmetatable(env, nil)
    end
    
    file1 = include'File1.lua'
    A = 1
    
    print(A)       -- 1
    print(file1.A) -- 5