1
1
-- A generic fifo module. See docs/lua-modules/fifo.md for use examples.
2
2
3
- local tr , ti = table.remove , table.insert
3
+ local tableRemove , tableInsert = table.remove , table.insert
4
4
5
5
-- Remove an element and pass it to k, together with a boolean indicating that
6
6
-- this is the last element in the queue; if that returns a value, leave that
@@ -17,29 +17,33 @@ local tr, ti = table.remove, table.insert
17
17
--
18
18
-- Returns 'true' if the queue contained at least one non-phantom entry,
19
19
-- 'false' otherwise.
20
- local function dequeue (q ,k )
21
- if # q > 0
22
- then
23
- local new , again = k (q [1 ], # q == 1 )
24
- if new == nil
25
- then tr (q ,1 )
26
- if again then return dequeue (q , k ) end -- note tail call
27
- else q [1 ] = new
28
- end
29
- return true
30
- else q ._go = true ; return false
20
+ local function dequeue (q , k )
21
+ if # q > 0 then
22
+ local new , again = k (q [1 ], # q == 1 )
23
+ if new == nil then
24
+ tableRemove (q , 1 )
25
+ else
26
+ q [1 ] = new
27
+ end
28
+ if again then
29
+ return dequeue (q , k )
30
+ end -- note tail call
31
+ return true
32
+ else
33
+ q ._go = true
34
+ return false
31
35
end
32
36
end
33
37
34
38
-- Queue a on queue q and dequeue with `k` if the fifo had previously emptied.
35
39
local function queue (q ,a ,k )
36
- ti (q ,a )
40
+ tableInsert (q ,a )
37
41
if k ~= nil and q ._go then q ._go = false ; dequeue (q , k ) end
38
42
end
39
43
40
44
-- return a table containing just the FIFO constructor
41
45
return {
42
46
[' new' ] = function ()
43
- return { [' _go' ] = true ; [' queue' ] = queue ; [' dequeue' ] = dequeue }
44
- end
47
+ return { [' _go' ] = true ; [' queue' ] = queue ; [' dequeue' ] = dequeue }
48
+ end
45
49
}
0 commit comments