Lua 模組 Shelve |
|
使用 shelve.open()
函式建立或開啟新的 shelf 檔案,如下所示
data = shelve.open("my_data_file")
data
變數類似一個 Lua 表單,因此您可以儲存鍵值,並使用已知的 Lua 語法讀取它們
-- store some values data.aNumber = 10 data.aString = "this is a string" data.aTable = { "these", "are", "some", "strings", "contained", "in", "a", "nested", "table", nested = true, items = 9 } -- retrieve values, and print them print(data.aString) print("items: " .. data.aTable) for k,v in data.aTable do print(k,v) end
如果您想要知道 shelf 檔案中有哪些金鑰,請執行呼叫,彷彿 shelf 是個函式,然後會傳回一個與 shelf 檔案相同的金鑰表單
-- retrieve keys and print them keys = data() for key in keys do print(k) end
或
-- retrieve keys and print them for key in data() do print(k) end
若要手動關閉 shelf 檔案,只需將其指定為 nil
,然後 Lua GarbageCollection 便會為您關閉。只要將這行貼到上述範例,即可關閉檔案
data = nil
目前僅提供原始碼。最新版本為 0.33。0.33 之前的版本有錯誤,強烈建議更新至 0.33 以上版本。
您將需要 Lua 5.0 beta 或以上版本,以及 Gdbm 或 Ndbm。建議使用 Gdbm。目前的版本已在 MacOS X 10.2 (Jaguar) 與 Linux 上進行測試。