是否可以根据我的Lua脚本而不是当前目录的位置进行导入? [英] Is it possible to make imports depend on the location of my Lua script instead of the current directory?

查看:86
本文介绍了是否可以根据我的Lua脚本而不是当前目录的位置进行导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在同一目录中有两个互相引用的脚本

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

A/
   foo.lua
   bar.lua

foo.lua

require "bar"

bar.lua

print "It worked"

然后从同一文件夹运行lua可执行文件

then running the lua executable from the same folder works

cd A; lua foo.lua

但是从另一个文件夹运行解释器失败,并显示找不到模块'bar'"消息

but running the interpreter from another folder fails with a "module 'bar' not found" message

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

有没有办法让我的相对进口不依赖于当前的工作目录?例如,在批处理文件中,我可以将路径设置为相对于dirname $0.

Is there a way to have my relative imports not depend on the current working directory? For example, in batch files I can setup my paths to be relative to dirname $0.

推荐答案

主要问题是package.path不考虑正在运行的脚本所在的目录.尽管道格(Doug)的解决方案有效,但如果您必须保留该目录,可能会变得很乏味.添加

The main issue is that package.path doesn't consider the directory the running script is in. While Doug's solution works this can become tedious if you have to keep adding

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

用于计划从其他工作目录运行的脚本.您可以做的很简单,就是创建一个模块,该模块会在需要时自动将运行脚本的目录添加到package.path.该模块将驻留在package.path中列出的默认位置之一中,以便可以找到它.

to scripts you plan on running from a different working directory. What you can do to make it easier is create a module that automatically adds the running script's directory to package.path when you require it. This module would reside in one of the default locations listed in package.path so 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"

实际上,这是一个常见的问题, Penlight 处理此问题的便利工具: pl.app.require_here .

In fact, this is a common enough problem that Penlight includes a convenience facility for handling this: pl.app.require_here.

这篇关于是否可以根据我的Lua脚本而不是当前目录的位置进行导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆