Go Back   Cockos Incorporated Forums > REAPER Forums > ReaScript, JSFX, REAPER Plug-in Extensions, Developer Forum

Reply
 
Thread Tools Display Modes
Old 01-25-2020, 10:09 AM   #1
spk77
Human being with feelings
 
Join Date: Aug 2012
Location: Finland
Posts: 2,668
Default Lua: Tip - Safely remove items from an array table while iterating

I was searching for the best way to remove values from an array-like table and I found this function:https://stackoverflow.com/questions/...hile-iterating.

table.remove is slow:
  • table.remove causes all of the subsequent (following) array indices to be re-indexed every time you call it to remove an array entry.


This function removes values and compacts/re-indexes the table within a single loop:
Code:
------------------------------------------------------------
function table_remove(t)
  local new_index = 1
  local n = #t
  for old_index = 1, n do
    local value = t[old_index]
    -- (This is a random example - remove every other value from the table)
    if value%2 == 0 then -- KEEP if true...
      -- Move old_index's kept value to new_index's position, if it's not already there.
      if old_index ~= new_index then
        t[new_index] = t[old_index]
        t[old_index] = nil
      end
      new_index = new_index + 1 -- Increment position of where we'll place the next kept value.
    else -- ... else REMOVE
      t[old_index] = nil
    end
  end
  return t
end

-- Example:
local t = {1,2,3,4,5,6,7,8,9,10}

reaper.ClearConsole()

for i=1, #t do
  reaper.ShowConsoleMsg(tostring(t[i]) .. " ")
end
reaper.ShowConsoleMsg("\nOriginal table length = " .. tostring(#t) .. "\n")

t = table_remove(t)

reaper.ShowConsoleMsg("\n")
for i=1, #t do
  reaper.ShowConsoleMsg(tostring(t[i]) .. " ")
end
reaper.ShowConsoleMsg("\nTable length after removing values = " .. tostring(#t))
spk77 is offline   Reply With Quote
Old 01-26-2020, 01:56 AM   #2
deeb
Human being with feelings
 
deeb's Avatar
 
Join Date: Feb 2017
Posts: 4,820
Default

Maybe create just a new table with the valid values and then set this table as the original one ! Is it that slow?
deeb is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -7. The time now is 01:05 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.