1if not modules then modules = { } end modules ['luat-sta'] = {
2 version = 1.001,
3 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
4 copyright = "PRAGMA ADE / ConTeXt Development Team",
5 license = "see context related readme files"
6}
7
8
9
10local gmatch, match = string.gmatch, string.match
11local type = type
12
13states = states or { }
14local states = states
15
16states.data = states.data or { }
17local data = states.data
18
19states.hash = states.hash or { }
20local hash = states.hash
21
22states.tag = states.tag or ""
23states.filename = states.filename or ""
24
25function states.save(filename,tag)
26 tag = tag or states.tag
27 filename = file.addsuffix(filename or states.filename,'lus')
28 io.savedata(filename,
29 "-- generator : luat-sta.lua\n" ..
30 "-- state tag : " .. tag .. "\n\n" ..
31 table.serialize(data[tag or states.tag] or {},true)
32 )
33end
34
35function states.load(filename,tag)
36 states.filename = filename
37 states.tag = tag or "whatever"
38 states.filename = file.addsuffix(states.filename,'lus')
39 data[states.tag], hash[states.tag] = (io.exists(filename) and dofile(filename)) or { }, { }
40end
41
42local function set_by_tag(tag,key,value,default,persistent)
43 local d, h = data[tag], hash[tag]
44 if d then
45 if type(d) == "table" then
46 local dkey, hkey = key, key
47 local pre, post = match(key,"(.+)%.([^%.]+)$")
48 if pre and post then
49 for k in gmatch(pre,"[^%.]+") do
50 local dk = d[k]
51 if not dk then
52 dk = { }
53 d[k] = dk
54 elseif type(dk) == "string" then
55
56
57 break
58 end
59 d = dk
60 end
61 dkey, hkey = post, key
62 end
63 if value == nil then
64 value = default
65 elseif value == false then
66
67 elseif persistent then
68 value = value or d[dkey] or default
69 else
70 value = value or default
71 end
72 d[dkey], h[hkey] = value, value
73 elseif type(d) == "string" then
74
75 data[tag], hash[tag] = value, value
76 end
77 end
78end
79
80local function get_by_tag(tag,key,default)
81 local h = hash[tag]
82 if h and h[key] then
83 return h[key]
84 else
85 local d = data[tag]
86 if d then
87 for k in gmatch(key,"[^%.]+") do
88 local dk = d[k]
89 if dk ~= nil then
90 d = dk
91 else
92 return default
93 end
94 end
95 if d == false then
96 return false
97 else
98 return d or default
99 end
100 end
101 end
102end
103
104states.set_by_tag = set_by_tag
105states.get_by_tag = get_by_tag
106
107function states.set(key,value,default,persistent)
108 set_by_tag(states.tag,key,value,default,persistent)
109end
110
111function states.get(key,default)
112 return get_by_tag(states.tag,key,default)
113end
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212 |