I’m trying to loadfile a script that has extra directories for require to search in in.
I have this file structure:
.
├── hidden
│ └── a.lua
└── main.lua
a.lua:
return "I was found"
main.lua:
local env = setmetatable(
{ package = setmetatable(
{ path = './hidden/?.lua;' .. package.path }, { __index = _ENV.package })
}, { __index = _ENV }
) -- Here i'm trying to create a custom `_ENV`, which points to the current `_ENV` except for the package.path variable.
print(load("return package.path", nil, "t", env)()) -- does indeed print './hidden/?.lua;...'
print(load("return require('a')", nil, "t", env)()) -- module 'a' not found
Am I misunderstanding how package.path works, or is the problem somewhere else?
Thanks for any help
>Solution :
Reading the Lua source, require doesn’t look up _ENV.package, it uses an upvalue to refer to the "package" table. This means that in your example, _ENV.package is no longer the table used internally by require and so _ENV.package.path is not the package.path that is actually used.
One way around it would be to do something like:
local oldpath = package.path
package.path = './hidden/?.lua;' .. package.path
print(load("return package.path", nil, "t", env)())
print(load("return require('a')", nil, "t", env)())
package.path = oldpath