darraghd493

ShiftList

Jan 2nd, 2025 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.56 KB | Source Code | 0 0
  1. --[[
  2.     ShiftList by darraghd493
  3.  
  4.     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.
  5.     This is useful for storing a fixed number of elements in a list, such as a history of values.
  6. ]]
  7.  
  8. local ShiftList = {
  9.     -- Internal properties
  10.     size = 0;
  11.     items = {};
  12. }
  13. ShiftList.__index = ShiftList
  14.  
  15. function ShiftList.new(size: number)
  16.     local self = setmetatable({
  17.         size = size;
  18.         items = {};
  19.     }, ShiftList)
  20.     for i=1,size do
  21.         self.items[i] = nil
  22.     end
  23.     return self
  24. end
  25.  
  26. function ShiftList:push(item: any)
  27.     for i=1,self.size-1 do
  28.         self.items[i+1] = self.items[i]
  29.     end
  30.     self.items[1] = item
  31. end
  32.  
  33. function ShiftList:get(index: number)
  34.     return self.items[index]
  35. end
  36.  
  37. function ShiftList:set(index: number, item: any)
  38.     self.items[index] = item
  39. end
  40.  
  41. function ShiftList:remove(index: number)
  42.     for i=index,self.size-1 do
  43.         self.items[i] = self.items[i+1]
  44.     end
  45.     self.items[self.size] = nil
  46. end
  47.  
  48. function ShiftList:find(item: any)
  49.     for i=1,self.size do
  50.         if self.items[i] == item then
  51.             return i
  52.         end
  53.     end
  54.     return nil
  55. end
  56.  
  57. function ShiftList:contains(item: any)
  58.     return self:find(item) ~= nil
  59. end
  60.  
  61. function ShiftList:clear()
  62.     for i=1,self.size do
  63.         self.items[i] = nil
  64.     end
  65. end
  66.  
  67. function ShiftList:iterate()
  68.     local index = 0
  69.     return function()
  70.         index = index + 1
  71.         return self.items[index]
  72.     end
  73. end
  74.  
  75. return ShiftList
Tags: lua scripting
Advertisement
Add Comment
Please, Sign In to add comment