更新时间: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
.package.path
.lua
at the end of the file.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
.