且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取Lua中的当前工作目录

更新时间:2023-01-27 15:14:15

Lua默认没有支持当前目录"或目录"概念的本机"方式

Lua by default doesn't have a "native" way of supporting the concept of "current directory", or, in fact, the concept of "directory".

获取当前目录的正确方法是使用提供文件夹支持的库.有几种-我建议 luafilesystem .

The proper way to get the current directory is using a library that provides folder support. There are several - I recommend luafilesystem.

安装后,您可以通过执行以下操作获取当前目录:

Once it is installed, you can get the current directory by executing:

lfs.currentdir()

这将在Windows,Linux和Mac上运行.

This will work on windows, linux and mac.

请注意,尽管这些外部库通常包含一些二进制程序包.根据您的设置,您可能必须先对其进行编译才能使用.

Beware though that these external libraries usually involve some binary packages. Depending on your setup, you might have to compile it before being able to use it.

请注意,当通过require包含文件时,表达式{...}[1]返回require指令使用的路径.这不是确切的路径,因为:

Note that when a file is included via require, then the expression {...}[1] returns the path used by the require directive. It is not exactly the path because:

  • 它使用点分隔目录,并在文件末尾禁止.lua.
  • 它与初始化lua进程的路径有关
  • 这取决于 package.path
  • 的配置
  • It uses dots to separate directories and supresses the .lua at the end of the file.
  • It is relative to the path from which the lua process was initialized
  • It depends on the configuration of package.path

但是,如果您只需要文件的类似需求的路径"(也许需要文件旁边的文件),则可以通过在文件的最开始处执行此操作来获得它:

But if all you need is the "require-like path" of the file (maybe to require files next to it) then you can get it by doing this at the very beginning of the file:

local PATH = (...):match("(.+)%.[^%.]+$") or (...)

如果require 'foo.bar.baz'需要一个名为baz.lua的文件,则PATH将为foo.bar.

If a file called baz.lua is required with require 'foo.bar.baz', then PATH will be foo.bar.