Table.remove(t, nil) removes the last value in an array

I am not sure if this behavior has changed at all, and if this is intended behavior and has always worked like this please ignore this post. For as long as I can remember this code worked, but I might have been mistaken this entire time

From my experience, table.remove(t, nil) would not remove any values from an array. This made it very useful for removing an item from an array using table.find only if that value exists, eg table.remove(t, table.find(t, "value")). This line of code no longer works because it will remove the last item in the array

local Values = {5, 4, 3, 2, 1}
local Remove = {8, 9, 10, 11, 12}

for _, Value in Remove do
	table.remove(Values, table.find(Values, Value))
end

print(Values) -- Will now print an empty table, used to print full table

Running this adjusted code in lua5.1 results in removal of the last value:

local Values = {5, 4, 3, 2, 1}

table.remove(Values, nil)

for k,v in pairs(Values) do print(k,v) end
$ lua5.1 test.lua
1	5
2	4
3	3
4	2

This is also consistent with Lua 5.4 as well as Luau. So I believe you’re mistaken and nil always was treated the same as absence of the second argument - in which case table.remove removes the last element.

5 Likes

Would be nice if there was a built in version of table.remove that removes elements based on their value rather than key. Having to set a variable to the key and check if it exists, then remove it if it does isn’t great and being able to do it in one line was great (even if i was wrong)

-- Wrong solution
table.remove(Table, table.find(Table, SomeValue))

-- Current safe solution
local Index = table.find(Table, SomeValue)

if (Index) then
	table.remove(Table, Index)
end

-- Possible solution, should not error if SomeValue isn't in the table
table.removeValue(Table, SomeValue)