There are two script files with the following script
//parent.lua
function scope()
local var = "abc"
require "child"
end
//child.lua
print(var)
This way, child.lua will print a nil value because the scope in parent.lua does not expose its local features to the module. I thought it would, since the require directive is stated within this scope and after the declaration of var. My desire is to practically wholly inject all the lines of the child into the parent. The child script is just exported for better readability. How can I pass the local scope? loadfile() did not work, nor did dofile(). The function environment fenv does not harbor local values. debug.setlocal() does not seem to be able to create new variables (also it would require a receiver in the child). Any method besides recompiling the script?
You can with a bit of effort. If your variables in
child
are real upvalues you can "link" them to values in yourscope
function. If they are global variables (which seems to be the case here), you can map them to an environment usingsetfenv
and populate that environment with values from your local variables.The following will print
abc
as you'd expect (you can changeloadstring
toloadfile
with the same effect):This is all for Lua 5.1, but it's also possible in Lua 5.2.