5

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.

Community
  • 1
  • 1
TomB
  • 53
  • 3

1 Answers1

6

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
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
  • Thank you! I didn't think any solution like this would work because i was using my own version of loadfile, but my understanding of how it was wrapped was wrong... – TomB Jul 16 '13 at 10:42
  • asserting pcall doesn't make any sense. – daurnimator Jul 16 '13 at 19:34
  • I can see what daurnimator means. If you intend for ill-formed scripts to fail, why not just call it regularly instead of going through the whole `assert(pcall` business? – greatwolf Jul 16 '13 at 21:05