1: Create a two-way queue
List = {First =1,last = 0}
function List:pushfirst (value)--Put a value from the beginning
Local F = self.first-1--f=0
SELF[F] = value--self[0] = value
Self.first =f--SELF.F = 0
--print (SELF.FIRST,F)
End
function List:pushlast (value)--Put a value from the tail
Local l= self.last+1
SELF[L] = value
Self.last = L
End
function List:popfirst ()--Launches the first value
if (Self.first > Self.last) Then
Print ("Warning: queue is empty")
return Nil
End
--print ("Come in when first index:", Self.first)
Local v = Self[self.first]
--print ("The first to be launched:", Self[self.first])
Self[self.first] = Nil
Self.first = Self.first + 1
--print ("list First index:", Self.first)
Return V
End
function List:poplast ()--Launch last value
if (Self.first > Self.last) Then
Print ("Warning: queue is empty")
return Nil
End
Local v = self[self.last]
Self[self.last] = Nil
Self.last =self.last-1
Return V
End
List:pushfirst (11)
List:pushfirst (22)
List:pushfirst (33)
List:pushlast (44)
List:pushlast (55)
--put 3 from back into 2 33 22 11 44 55
Print (List:poplast ())--last 55
List:pushlast (99)--33 22 11 44 99
List:pushfirst ("Orz")--orz "33 22 11 44 99
Print (List:popfirst ())--first Orz
======== then push the rest of the ==========.
Print (List:popfirst ())--5->orz remaining
Print (List:popfirst ())--4 33 remaining
Print (List:popfirst ())--3 22 remaining
Print (List:popfirst ())--2 11 remaining
Print (List:popfirst ())--1 44 remaining
Print (List:popfirst ())--0 99 remaining
Print (List:popfirst ())--0 empty warnings left
Lua learns the 9-14_03 data structure---> Queue (it's written in the same book)