You can write your topic however you want, but you need to answer these questions:
1.I am trying to remove all numbers under 5
The problem is it only removes 1 and 3
I have tried literally everything
I have ran into this issue with a more complex ipairs loop, i am using this as a debugging/testing sample of code.
local t = {1, 2, 3, 4, 5, 5, 5, 6};
for i, v in ipairs(t) do
if v < 5 then
table.remove(t, i);
end;
end;
print(t);
output:
2
4
5
5
5
6
Please help, i know that
local t = {1, 2, 3, 4, 5, 5, 5, 6};
for i, v in ipairs(t) do
if v < 5 then
print(t[i])
table.remove(t, i);
print(t[i]);
continue;
end;
print(v)
end
print(t)
^ that works, but i don’t want to do t[i] = nil or it will lag, please help!
Not allowed to change the table while you are iterating over it!
When you do table.remove the rest of the table shifts down, so what happens is:
1 gets removed
2 gets skipped because it is now where 1 was, but the current index is the second number, which is now 3.
Same thing happens again, 3 gets removed, 4 gets skipped.
local s = 0 --How many items have been removed
for i = 1, #t do
if t[i - s] < 5 then
table.remove(t, i - s) --Minus s accounts for table shifting down
s = s + 1
end
end
t = {1, 2, 3, 4, 5, 5, 5, 6};
for i, v in ipairs(t) do
if v < 5 then
rawset(t, i, nil);
end;
end;
t[0] = nil --refreshed after a meta bypass 😎
print(t);
Don’t do this because if you remove an element in the middle of the list it will go from acting like a list to acting like a dictionary, the # operator wont work, iterators will handle it different, etc.
local function ShiftHandler(t, i, callback)
did_remove = callback(i)
if i == #t then
return
elseif did_remove == true then
ShiftHandler(t, i, callback)
else
ShiftHandler(t, i + 1, callback)
end;
end;
local t = {1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 4, 3, 5, 5};
local function sort(i)
local v = t[i]
if v < 5 then
table.remove(t, i)
return true
end
return false
end;
ShiftHandler(t, 1, sort)
print(t)
something I can recommend is using a function that filters this table out. Something like this
local sample = {1,2,3,4,5,6}
local function check(value)
if value < 5 then return false
return true
end
local function filter(array, filterFunction)
local newArray = {}
for _, v in array do
if not filterFunction(v) then continue end --Will insert into the new table IF its a truthy
table.insert(newArray, v)
end
return newArray
end
filter(sample, check)