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

查看:2631
本文介绍了获取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 Settings\username).

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

推荐答案

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.

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

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