Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modified package.path for loaded lua file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading