2011-10-06 53 views
1

我想將一個表寫入一個文件,該文件以其創建的日期和時間命名。 我可以打開硬編碼名稱的文件,寫入表格進去,象下面這樣:如何用lua中的當前日期和時間創建文件名?

FILENAME_EVENTS="Events.txt"   -- filename in string 
local fp=io.open(FILENAME_EVENTS, a)  -- open a new file with the file name 
io.output(FILENAME_EVENTS)  -- redirect the io output to the file 
-- write the table into the file 
for i, e in ipairs(eventlist) do io.write(e.title, e.category, e.ds, e.de, e.td) end 

但是當我嘗試:

FILENAME_EVENTS=os.date().."\.txt"   -- filename in string with date 
local fp=io.open(FILENAME_EVENTS, a)  -- open a new file with the file name 
io.output(FILENAME_EVENTS)  -- redirect the io output to the file 
-- write the table into the file 
for i, e in ipairs(eventlist) do io.write(e.title, e.category, e.ds, e.de, e.td) end 

我得到一個錯誤 壞參數#1 'output'(10/06/11 17:45:01.txt:無效參數) 堆棧回溯: [C]:in function'output'

爲什麼這個「10/06/11 17:45: 01.txt「是一個無效的參數?由於它包含空格或'/'?或者其他原因?

BTW,該平臺是WIN7專業版+的Lua 5.1.4勝利

+0

什麼平臺這是什麼?這不應該發生。 – cnicutar

+0

Win7 Pro + lua5.1.4 for win – xdan

回答

9

顯然,這既是/:是博克。第一個可能是因爲它被視爲目錄分隔符。這可以如下證明:

fn=os.date()..'.txt' 
print(io.open(fn,'w')) -- returns invalid argument 

fn=os.date():gsub(':','_')..'.txt' 
print(io.open(fn,'w')) -- returns nil, no such file or directory 

fn=os.date():gsub('[:/]','_')..'.txt' 
print(io.open(fn,'w')) -- returns file(0x...), nil <-- Works 

BTW,而不是使用奇怪GSUB和拼接技巧,你也可以考慮使用類似

fn=os.date('%d_%m_%y %H_%M.txt') 
+0

謝謝jpjacobs,它的工作原理。對不起,我不能投票給你回答,因爲我沒有15點聲望點:( – xdan

相關問題