Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
How to implement a queue using Lua — Gideros Forum

How to implement a queue using Lua

simwhisimwhi Member
edited September 2016 in Code snippets
Hi all,

Here's another example of a classic data structure using OOP:
 
Queue = Core.class()
 
function Queue:init(list)
 
  if not list then
    self.q     = {}
    self.first = 0
    self.last  = -1
  else
    self.q = list
    self.first = 1
    self.last  = #list
  end
end
function Queue:push(item)
  self.last = self.last + 1
  self.q[self.last] = item
end
function Queue:pop()
  --local first = self.first
  if self.first <= self.last then
    --local q = self.q
    local value = self.q[self.first]
    self.q[self.first] = nil
    self.first = self.first + 1
    return value
  end
end
function Queue:iterator()
  return function()
    return self:pop()
  end
end
function Queue:length()
  return (self.last-self.first+1)
end
Here is how to use it:
  local q = Queue.new({"apples", "oranges", "bananas"})
 
  q:push("strawberries")
  q:push("grapes")
 
  print("The queue length:  "..q:length())
  print("Pop off the queue: "..q:pop())
 
  for item in q:iterator() do
 
    print("Pop of the queue: "..item)
 
  end
+1 -1 (+3 / -0 )Share on Facebook

Comments

Sign In or Register to comment.