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.

1 Answer 1

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
3
  • 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
    Commented Jul 16, 2013 at 10:42
  • asserting pcall doesn't make any sense. Commented Jul 16, 2013 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
    Commented Jul 16, 2013 at 21:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.