Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- ShiftList by darraghd493
- A list that shifts all elements to the right when a new element is added, and removes the last element when the list is full.
- This is useful for storing a fixed number of elements in a list, such as a history of values.
- ]]
- local ShiftList = {
- -- Internal properties
- size = 0;
- items = {};
- }
- ShiftList.__index = ShiftList
- function ShiftList.new(size: number)
- local self = setmetatable({
- size = size;
- items = {};
- }, ShiftList)
- for i=1,size do
- self.items[i] = nil
- end
- return self
- end
- function ShiftList:push(item: any)
- for i=1,self.size-1 do
- self.items[i+1] = self.items[i]
- end
- self.items[1] = item
- end
- function ShiftList:get(index: number)
- return self.items[index]
- end
- function ShiftList:set(index: number, item: any)
- self.items[index] = item
- end
- function ShiftList:remove(index: number)
- for i=index,self.size-1 do
- self.items[i] = self.items[i+1]
- end
- self.items[self.size] = nil
- end
- function ShiftList:find(item: any)
- for i=1,self.size do
- if self.items[i] == item then
- return i
- end
- end
- return nil
- end
- function ShiftList:contains(item: any)
- return self:find(item) ~= nil
- end
- function ShiftList:clear()
- for i=1,self.size do
- self.items[i] = nil
- end
- end
- function ShiftList:iterate()
- local index = 0
- return function()
- index = index + 1
- return self.items[index]
- end
- end
- return ShiftList
Advertisement
Add Comment
Please, Sign In to add comment