2014年9月27日 星期六

lua queue example

[code]
queue = {}
           
function queue.new()
  return { first = 1, last = 0 }
end

function queue.push( Q, value)
  local last = Q.last + 1
  Q.last = last
  Q[last] = value
end

function queue.pop(Q)
  local first = Q.first
  local last = Q.last
  if first > last then error("Q is empty") end
  local value = Q[first]
  Q[first] = nil
  if first >= last then
    Q.first = 1
    Q.last = 0
  else
    Q.first = first + 1
  end
  return value
end

function queue.size(Q)
  local first,last = Q.first,Q.last
  print(string.format("(%d,%d)",first,last))
  if (last < first) then return 0 end
  return last-first+1
end

nq = queue.new()
print("q'size1="..queue.size(nq))
-- queue.pop(nq)

for i = 1, 10 ,2  do
  queue.push( nq, i)
end
print("q'size2="..queue.size(nq))

for m = nq.first,nq.last do
  print(""..m.."]="..nq[m])
end

print("first "..nq[nq.first])
local v
v = nq.first       print(" v1 =".. v)
v = queue.pop(nq)  print("pop = "..v)

v = nq.first       print(" v2 =".. v)
v = queue.pop(nq)  print("pop = "..v)

for m = nq.first,nq.last do
  print(""..m.."]="..nq[m])
end

local n = queue.size(nq)
print("q'size3="..n)
for i=1,n do
    v=queue.pop(nq)
    print(""..i.."]="..v)
end

print("q'size4="..queue.size(nq))
print("#nq="..#nq)
[/code]


---- output ----
(1,0)
q'size1=0
(1,5)
q'size2=5
1]=1
2]=3
3]=5
4]=7
5]=9
first 1
 v1 =1
pop = 1
 v2 =2
pop = 3
3]=5
4]=7
5]=9
(3,5)
q'size3=3
1]=5
2]=7
3]=9
(1,0)
q'size4=0
#nq=0

標籤: , , ,