Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
TomB Avatar asked Jul 16 '13 10:07

TomB


1 Answers

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
like image 195
Egor Skriptunoff Avatar answered Sep 21 '22 05:09

Egor Skriptunoff