队列 Queue<T>(FIFO)

数组和集合

local Queue = {}
Queue.__index = Queue

function Queue.new()
  return setmetatable({items = {}, first = 1,
                       last = 0}, Queue)
end

-- New items go to the back
function Queue:push(value)
  self.last = self.last + 1
  self.items[self.last] = value
end

-- Move the front index; table.remove(t, 1)
-- would shift every item
function Queue:pop()
  if self:is_empty() then
    return nil
  end
  local value = self.items[self.first]
  self.items[self.first] = nil
  self.first = self.first + 1
  return value
end

function Queue:is_empty()
  return self.first > self.last
end

local int_queue = Queue.new()
int_queue:push(1)
int_queue:push(3)
int_queue:push(5)

-- Look at the head without removing it
local head = int_queue.items[int_queue.first]
-- head = 1
local first = int_queue:pop()
-- first = 1
local second = int_queue:pop()
-- second = 3
local third = int_queue:pop()
-- third = 5

local is_empty = int_queue:is_empty()
-- is_empty = true

print("head = " .. head)
print("first = " .. first)
print("second = " .. second)
print("third = " .. third)
print("is_empty = " .. tostring(is_empty))