无法在用户主目录中使用 io.open - Lua

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

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

问题是,它只在脚本的当前目录中创建configfile,而不是我刚刚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在我刚刚在用户主目录中创建的文件夹中创建文件的正确方法是什么?

我知道我在这里犯了一个初学者的错误,所以如果你浪费了时间,我道歉。

点赞
用户4801232
用户4801232

你遇到了 ~ 符号的问题。在你的 os.execute("cd ~/testdir") 中,是 shell 解释了这个符号,并将它替换为你的家目录路径。然而在 io.open("~/testdir/configfile.cfg", "w") 中,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") )
2015-11-03 10:12:46