-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstorage.lua
53 lines (44 loc) · 1.11 KB
/
storage.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
--[[
Copyright (c) 2014 Remko Tronçon
Licensed under the GNU General Public License v3.
See LICENSE for more information.
--]]
--
-- This module implements a persistent key/value storage.
--
local serialize = require('serialize')
local storage_mt = {}
local function load(file)
local storage = { file = file, data = {}}
local data_chunk = loadfile(file)
if data_chunk then
storage.data = data_chunk()
if type(storage.data) ~= "table" then
storage.data = {}
end
end
setmetatable(storage, storage_mt)
return storage
end
local function save(storage)
local f = io.open(storage.file, 'w')
f:write('return ' .. serialize.serialize(storage.data))
f:close()
end
local function get_setting(storage, key)
return storage.data[key]
end
local function set_setting(storage, key, value)
if type(key) ~= 'string' then error("Setting key needs to be a string") end
if not serialize.serialize(value) then error("Setting value is not serializable") end
storage.data[key] = value
save(storage)
end
storage_mt.__index = {
save = save,
get_setting = get_setting,
set_setting = set_setting
}
return {
load = load
}