Queue.lua 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. Queue = {}
  2. function Queue.new ()
  3. return {first = 1, last = 0}
  4. end
  5. function Queue.push (queue, value)
  6. local last = queue.last + 1
  7. queue.last = last
  8. queue[last] = value
  9. end
  10. function Queue.pop (queue)
  11. local first = queue.first
  12. if first > queue.last then error("queue is empty") end
  13. local value = queue[first]
  14. queue[first] = nil
  15. -- resize internal array
  16. local last = queue.last
  17. if first * 2 > last
  18. then
  19. for i = first + 1, last
  20. do
  21. queue[i - first] = queue[i]
  22. queue[i] = nil
  23. end
  24. queue.first = 1
  25. queue.last = last - first
  26. else
  27. queue.first = first + 1
  28. end
  29. return value
  30. end
  31. function Queue.push_back (queue, value)
  32. local first = queue.first
  33. if first > 1 then
  34. first = first - 1
  35. queue.first = first
  36. queue[first] = value
  37. else
  38. -- shift elements to right
  39. local last = queue.last
  40. for i = last,first,-1 do
  41. queue[i + 1] = queue[i]
  42. end
  43. queue[1] = value
  44. queue.first = 1
  45. queue.last = last + 1
  46. end
  47. end
  48. function Queue.remove (queue, index)
  49. local last = queue.last - 1
  50. queue.last = last
  51. for i = index,last-1 do
  52. queue[i] = queue[i + 1]
  53. end
  54. queue[last + 1] = nil
  55. end
  56. function Queue.size (queue)
  57. return queue.last - queue.first + 1
  58. end