[Lua] 取得檔案的最後修改時間

[Lua] 取得檔案的最後修改時間

想要用 Lua 取得檔案的最後修改時間 (last modified time),

上網查了一下,可以用 LuaFileSystem 完成~

安裝的話,可以使用 luarocks:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
luarocks install luafilesystem
luarocks install luafilesystem
luarocks install luafilesystem

 

以下用 Lua 直譯器來執行。

用 lfs.attributes() 可以取得一個檔案的屬性列表 (table):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> lfs = require("lfs")
> lfs.attributes("package.json")
table: 0x7fef0e904860
> lfs = require("lfs") > lfs.attributes("package.json") table: 0x7fef0e904860
> lfs = require("lfs")
> lfs.attributes("package.json")
table: 0x7fef0e904860

 

用迴圈看一下這個表格的內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> for k, v in pairs(lfs.attributes("package.json")) do print(k .. ": " .. v) end
ino: 54155609
permissions: rw-r--r--
access: 1609607041
rdev: 0
gid: 20
uid: 502
mode: file
blksize: 4096
blocks: 8
nlink: 1
change: 1609607041
modification: 1609607041
size: 679
dev: 16777220
> for k, v in pairs(lfs.attributes("package.json")) do print(k .. ": " .. v) end ino: 54155609 permissions: rw-r--r-- access: 1609607041 rdev: 0 gid: 20 uid: 502 mode: file blksize: 4096 blocks: 8 nlink: 1 change: 1609607041 modification: 1609607041 size: 679 dev: 16777220
> for k, v in pairs(lfs.attributes("package.json")) do print(k .. ": " .. v) end
ino: 54155609
permissions: rw-r--r--
access: 1609607041
rdev: 0
gid: 20
uid: 502
mode: file
blksize: 4096
blocks: 8
nlink: 1
change: 1609607041
modification: 1609607041
size: 679
dev: 16777220

 

當然你可以把 lfs.attributes() 的內容存在一個表格裡,

再去取裡面的屬性值來使用。

不過如果只想要取用某一個屬性值的話,

例如最後的修改時間 (modification) 或是檔案大小 (size) 時,

可以直接指定第二個參數,例如:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> lfs.attributes("package.json", "modification")
1609607041
> lfs.attributes("package.json", "size")
679
> lfs.attributes("package.json", "modification") 1609607041 > lfs.attributes("package.json", "size") 679
> lfs.attributes("package.json", "modification")
1609607041

> lfs.attributes("package.json", "size")
679

 

如果檔案不存在的話,取得的第一個回傳值會是 nil:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> lfs.attributes("not_exist", "modification")
nil cannot obtain information from file 'not_exist': No such file or directory 2
> lfs.attributes("not_exist", "modification") nil cannot obtain information from file 'not_exist': No such file or directory 2
> lfs.attributes("not_exist", "modification")
nil	cannot obtain information from file 'not_exist': No such file or directory	2

參考資料:file – How can I get last modified timestamp in Lua – Stack Overflow

(本頁面已被瀏覽過 152 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料