forked from mailru/tntlua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cnt.lua
49 lines (42 loc) · 1.11 KB
/
cnt.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
-- cnt.lua
--
-- Simple counter.
--
box.counter = {}
--
-- Increment counter identified by primary key.
-- Create counter if not exists.
-- Returns updated value of the counter.
--
function box.counter.inc(space, ...)
local key = {...}
local cnt_index = #key
local tuple
while true do
tuple = box.update(space, key, '+p', cnt_index, 1)
if tuple ~= nil then break end
local data = {...}
table.insert(data, 1)
tuple = box.insert(space, unpack(data))
if tuple ~= nil then break end
end
return box.unpack('i', tuple[cnt_index])
end
--
-- Decrement counter identified by primary key.
-- Delete counter if it decreased to zero.
-- Returns updated value of the counter.
--
function box.counter.dec(space, ...)
local key = {...}
local cnt_index = #key
local tuple = box.select(space, 0, ...)
if tuple == nil then return 0 end
if box.unpack('i', tuple[cnt_index]) == 1 then
box.delete(space, ...)
return 0
else
tuple = box.update(space, key, '-p', cnt_index, 1)
return box.unpack('i', tuple[cnt_index])
end
end