【Lua学习】循环队列实现:lua元表建立类

【Lua学习】循环队列实现:lua元表建立类

1、首先根据循环队列的理论(先入先出)想好类结构
2、学习lua的元表和元方法怎么建立类,访问冒号需要访问类里的局部成员变量 点访问模块的方法不需要变量

local Queue = {}

function Queue:new(len)
    local tempQue = {
        maxLength = len,
        size = 0,
        head = 0,
        tail = 0,
        que = {},
    }
    return setmetatable(tempQue, {__index = self})
end

function Queue:getSize()
    return self.size
end

function Queue:isEmpty()
    if self.size <= 0 then
        return true
    else 
        return false
    end
end

function Queue:isFull()
    if self.size == self.maxLength then
        return true
    else
        return false
    end
end

function Queue:push(id)
    if self:isFull() then
        --print("[queue] PUSH ERROR: QUEUE FULL")
        return false
    end
    local index = (self.tail % self.maxLength)
    self.que[index] = id
    --print("[queue] ", index, " ", self.que[index])
    self.tail = self.tail + 1
    self.size = self.size + 1
    --print("[queue] PUSH SUCCESS")
    return true
end

function Queue:pop()
    if self:isEmpty() then 
        --print("[queue] POP ERROR: QUEUE EMPTY")
        return false
    end
    id = self.que[Queue.head]
    self.head = self.head + 1
    self.head = self.head % self.maxLength
    self.size = self.size - 1
    return true, id
end

function Queue:top()
    return self.que[self.head]
end

function Queue:find(id)
    --print("[queue]head ", self.head, " tail ", self.tail)
    for i = self.head, self.size + self.tail - 1 do
        if self.que[i % self.maxLength] == id then 
            return true
        end
    end
    return false 
end

function Queue:clear()
    self.size = 0
    self.tail = 0
    self.head = 0
end

function Queue:deleteQueue()
    self.que = {}
    self.que = nil
    self.size = 0
    self.tail = 0
    self.head = 0
end

return Queue

你可能感兴趣的:(lua,STL,queue)