【问题标题】:Can't use io.open in home directory - Lua不能在主目录中使用 io.open - Lua
【发布时间】:2015-11-03 09:18:37
【问题描述】:

我正在编写一个 Mac OS 程序,我有以下几行:

os.execute("cd ~/testdir")
configfile = io.open("configfile.cfg", "w")
configfile:write("hello")
configfile:close()

问题是,它只在脚本当前目录中创建配置文件,而不是我刚刚 cd' 进入的文件夹。我意识到这是因为我使用控制台命令更改目录,然后直接 Lua 代码写入文件。为了解决这个问题,我将代码更改为:

configfile = io.open("~/testdir/configfile.cfg", "w")

但是我得到以下结果:

lua: ifontinst.lua:22: attempt to index global 'configfile' (a nil value)
stack traceback:
ifontinst.lua:22: in main chunk

我的问题是,使用 IO.Open 在我刚刚在用户主目录中创建的文件夹中创建文件的正确方法是什么?

我很感激我在这里犯了一个新手错误,所以如果你在我身上浪费你的时间,我很抱歉。

【问题讨论】:

  • os.execute("cd ~/testdir") 无法按预期工作,因为更改子进程中的当前目录不会影响父进程。

标签: macos io lua


【解决方案1】:

~ 符号有问题。在您的os.execute("cd ~/testdir") 中是解释符号并将其替换为您的主路径的shell。但是,io.open("~/testdir/configfile.cfg", "w") 是接收字符串的 Lua,而 Lua 不解释此符号,因此您的程序会尝试在不正确的文件夹中打开文件。一种简单的解决方案是调用os.getenv("HOME") 并将路径字符串与您的文件路径连接起来:

configfile = io.open(os.getenv("HOME").."/testdir/configfile.cfg", "w")

为了改善错误信息,我建议您使用assert() 函数包装io.open()

configfile = assert( io.open(os.getenv("HOME").."/testdir/configfile.cfg", "w") )

【讨论】:

  • 这行得通。我真的很感谢你的回答。我从来没有想过 io.open 不解释 ~ 符号。我从我的错误中吸取了教训。谢谢你。 @弗朗西斯科
猜你喜欢
  • 2014-07-21
  • 2015-01-01
  • 2011-03-12
  • 2023-04-07
  • 2017-04-10
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
相关资源
最近更新 更多