Lua 模組 Shelve

lua-users home
wiki

shelve 是個 Lua 模組,能透明地將 Lua 值(數字、字串、布林值與表單)編碼成檔案。每個儲存的元素都可以透過一個金鑰取得,以便使用 Lua 規則表單來處理 shelf 檔案。

快速秘訣

使用 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

作者

AdrianPerez

下載

目前僅提供原始碼。最新版本為 0.33。0.33 之前的版本有錯誤,強烈建議更新至 0.33 以上版本。

相依項

您將需要 Lua 5.0 beta 或以上版本,以及 Gdbm 或 Ndbm。建議使用 Gdbm。目前的版本已在 MacOS X 10.2 (Jaguar) 與 Linux 上進行測試。


近期變更 · 喜好設定
編輯 · 歷程
上次編輯時間為 2009 年 10 月 31 日,格林威治時間晚上 11:12 (diff)