Is it possible for the import to depend on the location of my Lua script instead of the current directory?

If I have two scripts that reference each other in the same directory

A/ foo.lua bar.lua 

foo.lua

 require "bar" 

bar.lua

 print "It worked" 

then running lua executable from the same folder works

 cd A; lua foo.lua 

but starting the interpreter from another folder fails with the message "module" not found message

 cd A/..; lua A/foo.lua 

Is there any way that my relative import is not dependent on the current working directory? For example, in batch files, I can configure my paths relative to dirname $0 .

+2
source share
2 answers

The main problem is that package.path does not take into account the directory where the running script is located. Although Doug's solution works, it can become tedious if you need to keep adding

 package.path = 'foobar_path/?.lua;'..package.path 

for scripts that you plan to run from another working directory. What you need to do to make it easier is to create a module that will automatically add the script working directory to package.path when you need it. This module will be in one of the default locations listed in package.path so that it can be found.

 -- moduleroot.lua local moduleroot = arg and arg[0] if moduleroot then local path = moduleroot:match [[^(.+[\/])[^\/]+$]] if path and #path > 0 then package.path = path..'?.lua;'..package.path package.cpath = path..'?.dll;'..package.cpath return path end end 

 -- foo.lua require "moduleroot" require "bar" 

This is actually a fairly common problem: Penlight includes a convenience tool to handle this: pl.app.require_here .

+2
source

The usual way to do this is to update package.path to contain the parent element of A (or put A in the path). Then use require and refer to modules like A.bar and A.foo

See the user manual for require

You can find the directory using debug.getinfo , but using the debug module in applications is a great idea and is not required in this case.

See this related SO question - use package.path .

+2
source

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


All Articles