Advertisement
gravitowl

Tabula

Dec 20th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.80 KB | None | 0 0
  1. function table:contains(searchValue, recursive)
  2.     recursive = recursive or false;
  3.  
  4.     local queue = {self};
  5.  
  6.     while #queue > 0 do
  7.         local entry = table.remove(queue, 1);
  8.         for _, value in pairs(entry) do
  9.  
  10.             if type(value) == "table" then
  11.                 if recursive then
  12.                     table.insert(queue, value);                  
  13.                 end
  14.             elseif value == searchValue then
  15.                 return true;
  16.             end
  17.         end
  18.     end
  19.  
  20.     return false;
  21. end
  22.  
  23. function table:print(indent)
  24.     indent = indent or 0;
  25.  
  26.     local spaceBefore = string.rep(" ", indent);
  27.     for key, value in pairs(self) do
  28.  
  29.         if type(value) == "table" then
  30.             print(spaceBefore .. key .. ":");
  31.             table.print(value, indent + 2);
  32.         else
  33.             print(spaceBefore .. key .. ": " .. tostring(value));
  34.         end
  35.     end
  36. end
  37.  
  38. function table:filter(predicate)
  39.     local result = {};
  40.  
  41.     for _, value in pairs(self) do
  42.         if predicate(value) then
  43.             table.insert(result, value);
  44.         end
  45.     end
  46.  
  47.     return result;
  48. end
  49.  
  50. function table:equal(other, recursive)
  51.     if self == other then return true end;
  52.     recursive = recursive or false;
  53.  
  54.     local selfKeyCount = 0;
  55.     for key, value in pairs(self) do
  56.         selfKeyCount = selfKeyCount + 1;
  57.  
  58.         if other[key] == nil or not (value == other[key]) then
  59.             return false;
  60.         end
  61.  
  62.         if recursive and type(value) == "table" then
  63.             if not table.equal(value, other[key]) then
  64.                 return false;
  65.             end
  66.         end
  67.      end
  68.  
  69.     local otherKeyCount = 0;
  70.  
  71.     for _, _ in pairs(other) do
  72.         otherKeyCount = otherKeyCount + 1;
  73.     end
  74.  
  75.     return selfKeyCount == otherKeyCount;
  76. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement