Advertisement
nakra

Untitled

Dec 17th, 2023
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.92 KB | None | 0 0
  1. function removeByKey(tab, val)
  2.   local found = false
  3.   -- Iterate through the table in reverse order
  4.   for i = #tab, 1, -1 do
  5.     if tab[i] == val then
  6.       table.remove(tab, i)
  7.       -- Remove the element at index i
  8.       found = true
  9.     end
  10.   end
  11.   -- If any elements were removed, create a new table with reset indices
  12.   if found then
  13.     local newTable = {}
  14.     for i, v in ipairs(tab) do
  15.       newTable[i] = v
  16.     end
  17.     return newTable
  18.   else
  19.     return tab
  20.     -- Value not found, return the original table
  21.   end
  22. end
  23.  
  24. function removeAndRebuild(tab, index)
  25.   -- Check if the index is valid
  26.   if index < 1 or index > #tab then
  27.     print("Invalid index")
  28.     return tab
  29.   end
  30.   -- Remove the element at the specified index
  31.   table.remove(tab, index)
  32.   -- Rebuild the table without nil values
  33.   local newTable = {}
  34.   for i, v in ipairs(tab) do
  35.     newTable[#newTable + 1] = v
  36.   end
  37.   return newTable
  38. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement