function class(classname, super) local superType = type(super) local cls if superType ~= "table" then superType = nil super = nil end if super then cls = {} setmetatable(cls, {__index = super}) cls.super = super else cls = {ctor = function() end} end cls.__cname = classname cls.__ctype = 2 cls.__index = cls function cls.new(...) local instance = setmetatable({}, cls) instance.class = cls instance:ctor(...) return instance end return cls end
--[[ lua队列(下标从1开始) create by jiangcheng_m ]] local Queue = class("Queue") function Queue:ctor() self:Clear() end function Queue:Enqueue(item) self.m_LastIndex = self.m_LastIndex + 1 self.m_Cache[self.m_LastIndex] = item end function Queue:Dequeue() local item = self:Peek() if item then self.m_Cache[self.m_FirstIndex] = nil self.m_FirstIndex = self.m_FirstIndex + 1 return item end return nil end function Queue:Peek() if self.m_FirstIndex > self.m_LastIndex then return nil end return self.m_Cache[self.m_FirstIndex] end function Queue:Count() return self.m_LastIndex - self.m_FirstIndex + 1 end function Queue:ToArray() local list = {} for i = self.m_FirstIndex,self.m_LastIndex do table.insert(list,self.m_Cache[i]) end return list end function Queue:GetElement(i) local offset = self.m_FirstIndex - 1 local itemIndex = i + offset return self.m_Cache[itemIndex] end function Queue:Clear() self.m_Cache = {} self.m_FirstIndex = 1 self.m_LastIndex = 0 end return Queue
测试
local Queue = require("Utility/Queue") local queue = Queue.new() queue:Enqueue(1) queue:Enqueue(2) queue:Enqueue(3) queue:Enqueue(4) print(queue:Count()) print("-------------------") print(queue:Peek()) print(queue:Count()) print("-------------------") print(queue:Dequeue()) print(queue:Count()) print("-------------------") queue:Enqueue(5) print(queue:Count()) print("-------------------") local count = queue:Count() for i = 1,count do print(queue:GetElement(i)) end print("-------------------") queue:Clear() print(queue:Count()) print("-------------------") print(tostring(queue:Dequeue()))
结果
文章评论