序文
以前、両端キューについてブログ記事を投稿しました。この固定長キューは、以前の構造に基づいて変更されます。
LUA はデータ構造を実装します: 両端キュー
このデータ構造は、ゲーム内のさまざまなレコードで確認できます。たとえば、宝くじの記録は常に置き換えられ、後で生成された記録が以前の記録を置き換えます。
クライアントは表示時に10件表示する必要があるかもしれませんが、20件などを保存しておくと良いでしょう。
コード
固定長キューは実際には FIFO キューで、一方の端が入力し、もう一方の端から出力されます。キューのサイズは固定です。元のキューに基づいて、キューの現在の長さを示すために長さを追加し
、 max_length はキューの最大長を示します。
チームに入る際にmax_lengthより大きいかどうかを判断し、大きい場合はアドバンスト要素をポーリングします。
最後に、最後の N 要素を取得するメソッドが提供されます。
新しいファイル名:fixed_length_queue.lua
local List = {
}
List.__index = List
function List:new(max_length)
assert(max_length)
local self = {
first = 0, last = -1, length = 0, max_length = max_length}
return setmetatable(self, List)
end
function List:push(value)
local last = self.last + 1
self.length = self.length + 1
self.last = last
self[last] = value
if self.length > self.max_length then
self:poll()
end
end
function List:poll()
local first = self.first
if first > self.last then error("list is empty") end
local value = self[first]
self[first] = nil -- to allow garbage collection
if first == self.last then
self.first = 0
self.last = -1
else
self.first = first + 1
end
self.length = self.length - 1
return value
end
-- should not change the self in func
-- func return break or not
function List:foreach(func, right_first)
if right_first then
for i = self.last, self.first, -1 do
if func(self[i]) then break end
end
else
for i = self.first, self.last do
if func(self[i]) then break end
end
end
end
function List:clear()
if not self:empty() then
for i = self.first, self.last do
self[i] = nil
end
end
self.first = 0
self.last = -1
end
function List:to_table()
local res = {
}
for i = self.first, self.last do
table.insert(res, self[i])
end
return res
end
function List:get_last_n_rcd(n)
local res = {
}
for i = 0, n - 1 do
if self.first > self.last - i then return res end
table.insert(res, self[self.last - i])
end
return res
end
return List
テストコード
テストコードは次のとおりです。
local List = require("fixed_length_queue")
local list = List:new(10)
for i = 1, 20 do
list:push(i)
end
list:foreach(print)
print("-----------------")
local ret = list:get_last_n_rcd(5)
for _, v in ipairs(ret) do
print(v)
end
結果:
11
12
13
14
15
16
17
18
19
20
-----------------
20
19
18
17
16