2015-11-03 20 views
4

我在寫一個Mac OS程序,我有以下行:不能在主目錄使用io.open - Lua的

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創建在一個文件的正確方法我剛在用戶主目錄中創建的文件夾?

我很欣賞我在這裏犯了一個菜鳥錯誤,所以我很抱歉如果你浪費我的時間。

+2

'os.execute (「cd〜/ testdir」)不能像你期望的那樣工作,因爲改變子進程中的當前目錄不會影響父進程。 – lhf

回答

5

您有~符號的問題。在您的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")) 
+1

這工作。我非常感謝你的回答。它從未想過io.open不解釋〜符號。我從我的錯誤中學到了東西。謝謝。 @Francisco –