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))