I am looking to remove an item from a table using lua
a quick search led me to read that table.remove() is a bad idea due to efficiency
however i'm not 100% understanding the custom function
here is the function
function ArrayRemove(t, fnKeep)
local j, n = 1, #t;
for i=1,n do
if (fnKeep(t, i, j)) then
-- Move i's kept value to j's position, if it's not already there.
if (i ~= j) then
t[j] = t[i];
t[i] = nil;
end
j = j + 1; -- Increment position of where we'll place the next kept value.
else
t[i] = nil;
end
end
return t;
end
i understand the idea that we move the items and remove all in one loop rather than the table.remove() having to move everything ( there is a long answer here about it, Safely remove items from an array table while iterating)
looking at the function above, what would happen if the item to delete is the first item?
if we replace the line if (fnKeep(t, i, j)) then
as suggested with (t[i] == 'deleteme')
then nothing happens as both i and j are 1
also if the first 'if' is false then the item is removed anyways?
can someone shed some light on this for me please
edit
I believe the working function would be as follows
local j, n = 1, #t -- t is table to iterate over
for i = 1, n do -- begin the loop
if t[i] ~= 'object to delete' then -- if this is NOT the item to remove
if i ~= j then -- can it be moved to new position
t[j] = t[i] -- move to new pos
t[i] = nil -- clear old pos
end
j = j + 1 -- increment the new pos counter
end
else -- if it is the item TO delete then delete it
t[i] = nil
end