Simple queue implementation in lua
When I started writing stuff in mudlet I realized that the utter lack of anything resembling proper data types in lua is problematic.
I wrote this simple queue implemention to simplify keeping things in a queue. I don't know if this will be useful to anyone, but I thought I'd share.
To create a new queue, do
your_queue=SimpleQueue:create()
to add items to the queue, do your_queue:add("some value")
to peek (look at the top element on the queue), do value=your_queue:peek()
to pop (get the top element in the queue and remove it from the queue) do value=your_queue:pop()
to get the number of items in the queue, your_queue:count()
Please let me know if this is helpful to anyone, as I plan implementing other data types.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MudletPackage>
<MudletPackage version="1.0">
<ScriptPackage>
<Script isActive="yes" isFolder="no">
<name>Queue</name>
<packageName></packageName>
<script>
SimpleQueue={}
SimpleQueue.__index=SimpleQueue
function SimpleQueue:create()
local queue={}
setmetatable(queue, SimpleQueue)
queue.__data__={}
queue.__count__=0
return queue
end
function SimpleQueue:add(value)
table.insert(self.__data__,value)
self.__count__=self.__count__+1
end
function SimpleQueue:peek()
if self.__count__ > 0 then
return self.__data__[1]
else
return nil
end
end
function SimpleQueue:pop()
if self.__count__ > 0 then
local value=self.__data__[1]
table.remove(self.__data__,1)
self.__count__=self.__count__-1
return value
else
return nil
end
end
function SimpleQueue:count()
return self.__count__
end
</script>
<eventHandlerList/>
</Script>
</ScriptPackage>
</MudletPackage>
1
Comments