2024年4月27日

在Lua中,获取当前目录的方法有多种,如:

  1. 使用 os.getcwd() 函数

    local current_dir = os.getcwd()

  2. 使用os.getenv函数获取当前工作目录的绝对路径:

    local current_dir = os.getenv("PWD")

  3. 使用io.popen函数执行pwd命令获取当前工作目录的绝对路径:

    local current_dir = io.popen("pwd"):read("*l")

  4. 使用os.execute函数执行cd命令并获取返回值:

    local current_dir = os.execute("cd")

  5. 使用io.lines函数读取当前工作目录的绝对路径:

    local current_dir = io.lines():read("*l")

  6. 使用io.lines函数读取当前工作目录的相对路径:

    local current_dir = io.lines():read("*l"):gsub("^%s*(.-)%s*$", "%1")

但是这些方法只局限在Unix/Linux系统上,在windows上基本不起作用。

目前在各种系统上能通用的方法是采用debug.getinfo函数的方法

local function getCurrentDirectory()
local path = debug.getinfo(1, "S").source:sub(2)
local directory = path:match("(.*/)")
return directory
end

或者

local function getCurrentDirectory()
local info = debug.getinfo(2)
local source = info.source
local directory = string.gsub(source, "^@(.*)/[^/]+%.lua$", "%1")
return directory
end

相关日志

  • 电脑出现类九宫格小屏的处理方法
    老了,我的电脑真的是老了,打开一个小小的程序居然就会死机。这一死机可是惊天地泣鬼神了,直接导致系统崩溃,屏幕分裂成了多个小屏,有点像九宫格,但又不是,说不太清楚,直接上图。  ...
  • 自由选择安装手机操作系统
          现在的手机操作系统竞争日趋激烈,很多手机厂商、软件公司、网络公司等都推出了自己的手机操作系统,想为自己在手机市场上占得一席之地。现在的手机...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注