Download a file and return its surroundings

I am trying 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 found exactly what I am looking for, but in lua 5.1 here: Download a file without polluting the 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 the registered version of the boot file, so I try not to change the call.Is function is this possible? No matter what I do, breaks or env is null.

+4
source share
1 answer

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 
+5
source

Source: https://habr.com/ru/post/1491621/


All Articles