在 Lua 中获取当前工作目录 [英] get current working directory in Lua

查看:69
本文介绍了在 Lua 中获取当前工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows XP SP3 上获取当前工作目录的 Lua 是什么(或获取当前运行的 Lua 文件的目录)?我更喜欢使用LuaFileSystem.

What's the Lua to get the current working directory on Windows XP SP3 (or to get the directory of the currently-running Lua file)? I prefer not to use LuaFileSystem.

我不能使用 os.execute("cd") 因为 os.execute 总是从我的主目录开始(因此总是产生 C:Documents and Settingsusername).

I can't use os.execute("cd") because os.execute always starts from my home directory (and thus always yields C:Documents and Settingsusername).

推荐答案

Lua 默认没有native"支持当前目录"概念或实际上是目录"概念的方式.

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<的配置/li>
  • 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.

这篇关于在 Lua 中获取当前工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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