File: buffer.lua

package info (click to toggle)
minetest-mod-basic-robot-csm 0.0~git20190703.e082c6a-2
  • links: PTS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 268 kB
  • sloc: makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,177 bytes parent folder | download
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
54
55
56
--buffer by rnd

buffer = {};
buffer.idx = 0
buffer.data = {};
buffer.t = 0 -- how many unread insertions

buffer.add = function(element) -- insert new element
	local i = buffer.idx+1;
	if i > buffer.size then i = 1 end
	buffer.data[i]=element
	buffer.idx = i
	local t = buffer.t +1
	if t>buffer.size then t = buffer.size end
	buffer.t =  t
end

buffer.read = function() -- pop 1 message, return nil if none
	local t = buffer.t; 
	if t>0 then
		buffer.t = t-1
		local idx = buffer.idx;
		if idx>1 then buffer.idx = idx - 1 else buffer.idx = buffer.size end
		return buffer.data[idx];
	end
end

buffer.last = function(count) -- returns list of "count" recently inserted elements
	local ret = {};
	local idx = buffer.idx;
	local size = buffer.size;
	if count > size then count = size end
	local data = buffer.data
	for i = idx,1,-1 do
		ret[#ret+1] = data[i];
	end
	
	if count > idx then
		for i = 1,count - idx do
			ret[#ret+1]=data[buffer.size-i+1]
		end
	end
	return ret
end



buffer.size =  3;
buffer.add(1);buffer.add(2);
--say(minetest.serialize(buffer.read()))
say("1 " .. buffer.read())
say(buffer.t)
say("2 " .. buffer.read())
say("3 " .. buffer.read())

self.remove()